我正在尝试通过单击"X按钮"删除输入字段.删除后,它将不会在提交表单时发布其值.出现"+按钮",允许用户再次添加所述输入.输入具有onclick打开日历的事件,重新附加后,日历不再单击打开.我不能使用jQuery.
adderBtn.onclick = function (e) {
var elem = that.hiddenElems.shift();
that.collectionItemContainer.append(elem);
}
removerBtn.onclick = function (e) {
collectionItemElem.remove();
that.hiddenElems.push(collectionItemElem);
}
Run Code Online (Sandbox Code Playgroud)
问题是如何在不丢失事件的情况下删除和重新附加DOM节点.
T.J*_*der 12
删除元素时,只要保留对它的引用,就可以将其放回去.所以:
var input = /*...code to get the input element*/;
input.parentNode.removeChild(input); // Or on modern browsers: `input.remove();`
Run Code Online (Sandbox Code Playgroud)
以后如果你想把它放回去
someParentElement.appendChild(input);
Run Code Online (Sandbox Code Playgroud)
与jQuery不同,DOM不区分"删除"和"分离" - DOM操作总是等同于"分离",这意味着如果你添加元素,它仍然有它的处理程序:
实例:
var input = document.querySelector("input[type=text]");
input.addEventListener("input", function() {
console.log("input event: " + this.value);
});
input.focus();
var parent = input.parentNode;
document.querySelector("input[type=button]").addEventListener("click", function() {
if (input.parentNode) {
// Remove it
parent.removeChild(input);
} else {
// Put it back
parent.appendChild(input);
}
});Run Code Online (Sandbox Code Playgroud)
<form>
<div>
Type in the input to see events from it
</div>
<label>
Input:
<input type="text">
</label>
<div>
<input type="button" value="Toggle Field">
</div>
</form>Run Code Online (Sandbox Code Playgroud)
如果你删除元素而不保留任何引用,它就有资格进行垃圾收集,就像任何附加到它的处理程序一样(假设没有其他任何引用它们,并且在这方面忽略了一些历史性的IE错误......).
| 归档时间: |
|
| 查看次数: |
1792 次 |
| 最近记录: |