js:<input> 字段在删除并重新添加到 DOM 后似乎在内存中两次

问题描述

我在 html 中有一个 <input> 元素,在按钮内:

HTML:

<button class="green button " id="playPause"> &nbsp;Play in&nbsp;&nbsp; <input type="text" 
 id="timeInputInButton" maxlength="3" size="2" value="3" 
 style="text-align:right; padding-bottom:1px; padding-top:1px; padding-right:2px; margin-bottom:0px; margin-top:0px;" > 
 sec </button> 

在 JS 中:

const timeInput = document.getElementById('timeInputInButton');

现在一切都按预期进行:当我现在说 timeInput.value = 100 时,显示的值跳转100

但是一旦我从 DOM 中删除 timeInput 然后(稍后)再次将它添加回来,它就好像我有 2 个 <input> 元素具有相同的 ìd

这就是我删除元素的方式(即使我使用 .removeChild() 也是一样):

const playPauseButton = document.getElementById('playPause');
playPauseButton.innerHTML = "Pause";

以及我如何重新添加它(使用 appendChildappend 无关紧要):

playPauseButton.appendChild(timeInput);

现在,如果我说 timeInput.value = 100,GUI 不会更新。

timeInput.value = 100,但是

document.getElementById('timeInputInButton').value 返回变量绑定时输入字段的认值 const timeInput = document.getElementById('timeInputInButton');

为什么看起来我的内存中有 2 个 <input> 元素?

解决方法

这无疑与 <button> 元素中不允许交互式内容有关。尽管浏览器允许这样做并尽其所能使有缺陷的封装工作,但不恰当地使用 HTML 会产生后果。 Reference