首页 > 解决方案 > js:删除并重新添加到 DOM 后,字段似乎在内存中两次

问题描述

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

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.

但是,一旦我timeInput从 DOM中删除<input>ìd.

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

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

appendChild以及我如何重新添加它(如果我使用or无关紧要append):

playPauseButton.appendChild(timeInput);

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

timeInput.value= 100,但是

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

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

标签: javascripthtmlhtml-inputhtmlbutton

解决方案


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


推荐阅读