Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following html:

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

When I call the following javascript:

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

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.

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

Update

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
678 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...