javascript-按钮需要被单击两次才能onclick触发 [英] javascript - button needs to be click twice for onclick to trigger

查看:375
本文介绍了javascript-按钮需要被单击两次才能onclick触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么需要两次单击我的按钮才能触发onclick事件? 在stackoverflow上还有其他一些线程也有同样的问题,但是在我发现的所有线程中,原始发布者都将事件处理程序放入了函数中.我的代码不是那样的.

Why does my button need to be clicked twice for the onclick event to trigger? There're some other thread on stackoverflow with the same problem, but in all the thread i found, the original poster puts the event handler inside the function. It's not like that with my code.

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>

脚本:

var parentList = document.getElementById("parentList");
document.getElementById("delete").onclick = function() {
    parentList.removeChild(parentList.firstChild);
};

演示:点击错误

推荐答案

parentList中的第一个元素"是空格.您可以通过控制台记录事件侦听器中的元素来查看此情况.

The first "element" within the parentList is whitespace. You can see this by console logging the element within the event listener.

因此,您只需要过滤出父项中的li元素.

You therefore need to only filter out the li elements within the parent item.

document.getElementById("delete").onclick = function() {
    var listItems = document.querySelectorAll("#parentList > li");

    if (listItems.length > 0) {
        listItems[0].remove();
    }
};

https://jsfiddle.net/ofLvac32/13/

您还可以使用parentList.firstElementChild 代替 parentList.firstChild,它会过滤掉所有无效节点(空白).

You could also use parentList.firstElementChild instead of parentList.firstChild, which filters out any invalid nodes (whitespace).

此示例

var parentList = document.getElementById("parentList");

document.getElementById("delete").onclick = function() {
    parentList.removeChild(parentList.firstElementChild);
};

https://jsfiddle.net/ofLvac32/37/

这篇关于javascript-按钮需要被单击两次才能onclick触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆