使用JavaScript模拟点击事件

3
我想要做的是将一个图像按钮放在比按钮本身更宽的 div 中,当点击外部 div 时,我希望调用图像按钮的 onclick() 函数。我预期下面的 HTML 代码能实现以下效果:当我单击按钮本身时,它应该只弹出 "button clicked" 的警告框;而当我单击外部的 div 时,它应该先弹出 "div clicked",然后是 "button clicked"。问题在于,当我单击 div 时,警告框的顺序是: 先是 "div clicked",然后是 "button clicked",最后还会再次弹出 "div clicked"。而当我单击按钮时,它的警告框顺序是:先是 "button clicked",然后是 "div clicked",最后还会再次弹出 "button clicked" 和 "div clicked"。我不知道自己漏掉了什么,有人能帮忙吗?
<html>
<body>
    <div style="width: 200px; border: 1px solid red;" onclick="alert('div clicked');(document.getElementById('addButton')).click();">
        <input type="button" onclick="alert('button clicked');"
            id="addButton"/>
    </div>
</body>
</html>

抱歉,代码格式有误,已进行修改。 - Use the fork Luke
https://dev59.com/B3E95IYBdhLWcg3wUMPW - 可能是重复问题 - Carlo Moretti
4个回答

2
您错过的事实是,某些事件会在文档树中冒泡,从而触发父元素的所有单击处理程序。要停止它,请在事件对象上调用stopPropagation。
<input type="button" onclick="event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);alert('button clicked');"
        id="addButton"/>

(在旧版 IE 中没有 stopPropagation 方法,需要设置 event.cancelBubble=true)


1
在Internet Explorer中,您可以简单地执行以下操作
myElement.click();

然而,W3标准要复杂一些。 以下代码应该适用于其他浏览器:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);
myElement.dispatchEvent(evt);

还可以参考这个问题:如何模拟单击锚标签?


0

使用 window.event.stopPropagation(); 就像这样

<div style="width: 200px; border: 1px solid red;" onclick="alert('div clicked');(document.getElementById('addButton')).click();">
    <input type="button" value="X" onclick="alert('button clicked');window.event.stopPropagation();"
        id="addButton"/>
</div>

0

你需要避免JavaScript中的事件冒泡,像这样:

<html>
<body>
    <script type="text/javascript">
        function clickOnDiv(e){
            alert('Div clicked.');
            document.getElementById('addButton').click();
            e.preventDefault();
            return false;
        }

    function clickOnButton(e){
        e.preventDefault();

        // This line to prevent event bubbling
        e.stopPropagation() ? e.stopPropagation() : (e.cancelBubble=true);

        alert('Button clicked.');
        return false;
    }


    </script>
    <div id='maDiv' style="width: 200px; border: 1px solid red;">
        <input type="button" value="Click Me !" id="addButton"/>
    </div>
    <script>
        (function(){
            document.getElementById('addButton').onclick = clickOnButton;
            document.getElementById('maDiv').onclick = clickOnDiv;
        })();
    </script>
</body>
</html>

测试通过.. :)


另外,我重构了你的代码,使其更符合DOM事件模型2级规范。 - pad31

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接