Nhu*_*yen 5 html javascript event-handling
为什么我的按钮需要点击两次以触发onclick事件?stackoverflow上有一些其他线程有同样的问题,但在我找到的所有线程中,原始海报将事件处理程序放在函数中.这与我的代码不一样.
HTML
<body>
<ul id="parentList">
<li>First child</li>
<li>Second child</li>
<li>Third child</li>
<li>Forth child</li>
<li>Fifth child</li>
</ul>
<button type="button" id="delete">Delete first child</button>
</body>
Run Code Online (Sandbox Code Playgroud)
脚本:
var parentList = document.getElementById("parentList");
document.getElementById("delete").onclick = function() {
parentList.removeChild(parentList.firstChild);
};
Run Code Online (Sandbox Code Playgroud)
parentList中的第一个"元素"是空格.您可以通过控制台在事件侦听器中记录元素来查看此信息.
因此,您只需要过滤掉li父项中的元素.
document.getElementById("delete").onclick = function() {
var listItems = document.querySelectorAll("#parentList > li");
if (listItems.length > 0) {
listItems[0].remove();
}
};
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/ofLvac32/13/
您也可以使用parentList.firstElementChild 而不是 parentList.firstChild过滤掉任何无效节点(空格).
这方面的一个例子
var parentList = document.getElementById("parentList");
document.getElementById("delete").onclick = function() {
parentList.removeChild(parentList.firstElementChild);
};
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/ofLvac32/37/
| 归档时间: |
|
| 查看次数: |
3880 次 |
| 最近记录: |