开发者

jQuery firing twice, event bubbling?

I have looked at all of the issues people are having with event bubbling and jQuery firing twice, but I can't figure out this issue. I am only clicking in one DIV at a time, but the click handler is firing twice.

HTML

<div class="scroll-content-item" data-pid="1773">
    <开发者_开发技巧img src="somefile" class="mixdock-img" data-pid="1773"/>
</div> 
<div class="scroll-content-item" data-pid="1777">
    <img src="someotherfile" class="mixdock-img" data-pid="1777"/>
</div> 

jQuery...

jQuery(document).ready(function($) {

var count = 0;

// On click, hide the currently displayed post and show the one clicked
$('.scroll-content-item').click(function () {
    count += 1;
    alert("count = "+count);
    event.stopPropagation();
});

});

What this does is show two alerts per click, each with the same count. Count does increment on each click.


You have to pass the event variable into your function like so:

$('.scroll-content-item').click(function (event) {


I was not able to reproduce the issue on jsbin: http://jsbin.com/ixabo4

Is it possible that you have included the jQuery script twice?


It sounds like overall your code is executing twice, two entire instances of your:

jQuery(document).ready(function($) {
  //...
});

...are executing (each with their own count variable), ensure the script isn't being included twice in the page. To confirm this is the issue, you can add an alert (which you should see twice at the moment):

jQuery(document).ready(function($) {
  alert("init");
  //...
});


jQuery(document).ready(function($) {

        var count = 0;

        // On click, hide the currently displayed post and show the one clicked
        $('.scroll-content-item').click(function(e, ui) {
            e.stopPropagation();
            count += 1;
            alert("count = " + count);
        });

    });

Works fine in my tests. Even with nested divs with the class "scroll-content-item". I would make sure you aren't attaching a listener to the click handler more than once.

If you can't find a place where the code is being called twice add the following before you attach the listener:

$('.scroll-content-item').unbind('click');


$('.scroll-content-item').unbind('click').bind('click', function(e) {
    alert("clicked");
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜