javascript - js:删除并重新添加到 DOM 后,字段似乎在内存中两次
问题描述
我<input>
在 html 中有一个元素,在一个按钮内:
HTML:
<button class="green button " id="playPause"> Play in <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
.
但是,一旦我timeInput
从 DOM中删除<input>
了ìd
.
这就是我删除元素的方式(即使我使用它也是一样的.removeChild()
):
const playPauseButton = document.getElementById('playPause');
playPauseButton.innerHTML = "Pause";
appendChild
以及我如何重新添加它(如果我使用or无关紧要append
):
playPauseButton.appendChild(timeInput);
现在,如果我说timeInput.value = 100
GUI 没有更新。
timeInput.value
= 100,但是
document.getElementById('timeInputInButton').value
返回变量绑定时输入字段的默认值const timeInput = document.getElementById('timeInputInButton');
为什么看起来我<input>
的内存中有 2 个元素?
解决方案
这无疑与元素内不允许交互内容有关<button>
。尽管浏览器允许这样做并尽其所能使有缺陷的封装工作,但不恰当地使用 HTML 会产生后果。参考