为什么onClick事件被触发两次? [英] Why is the onClick event triggered twice?

查看:1474
本文介绍了为什么onClick事件被触发两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html:

<span onclick="alert('Boem')">
    <button id="test1">test</button>
</span>

当我调用以下javascript时:

When I call the following javascript:

$('#test1').trigger('click');

onclick事件被触发两次,而我希望它仅触发一次.因为JQuery应该在DOM树中查找,并且只找到一个onclick.

The onclick event is triggered twice, while I expect it to just trigger once. Because JQuery should look up in the DOM tree and find only one onclick.

我没有控制范围,它是在第三方工具中生成的.我确实可以控制按钮及其参数.

I do not have control of the span, it is generated in a third party tool. I do have control over the button and his parameters.

您可以在这里找到一个JSFiddle示例: http://jsfiddle.net/Voga/v4100zke/

You can find a JSFiddle example here: http://jsfiddle.net/Voga/v4100zke/

我不知道该范围的onclick侦听器的内容.这也是由第三方工具生成的.我希望点击触发器像现在一样执行此onclick,但只能执行一次.

I do not know the contents of the onclick listener of the span. This is also generated by the 3rd party tool. I want the click trigger to execute this onclick like it does now, but only once.

推荐答案

它被调用两次,因为按钮位于范围内并且范围具有onclick="alert('Boem')",因此当您触发单击按钮时,它会显示警报并传播相同的单击事件跨越并再次显示警报.

It is calling twice because button is inside a span and span has onclick="alert('Boem')", hence when you trigger click on button then it shows alert and same click event propagate to span and shows alert once again.

您需要使用以下代码停止按钮的默认行为:

you need to stop default behaviour of button using below code :

$(function(){
$('#test1').click(function(e){e.preventDefault();}).click();
});

演示

Demo

这篇关于为什么onClick事件被触发两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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