开发者

Why does my function get called twice in jQuery?

I have the following jQuery

$('img[title*=\"Show\"]').click(function() {
        //$e.preventDefault();      
        var position = $('img[title*=\"Show\"]').parent().position();
        $('#popover').css('top', position.t开发者_StackOverflowop + $('img[title*=\"Show\"]').parent().height() + 150);
        console.log(position);
        $('#popover').fadeToggle('fast');
        if ($('img[title*=\"Show\"]').hasClass('active')) {
          $(this).removeClass('active');
        } else {
          $('img[title*=\"Show\"]').addClass('active');
        }
      });

I have two images with the title "Show Options." For some reason whenever I click on any of these images, it gets printed TWICE. When I only have 1 image, it only gets printed once. Why is this?


instead of $('img[title*=\"Show\"]') inside click function use $(this)
if doesn't works use:

$('img[title*=\"Show\"]').click(function(e) {
        e.stopImmediatePropagation();
        //other code
    });


Use the following code

    $('img[title*="Show"]').click(function (evt) {
        $('#popover').hide();
        $('img[title*="Show"]').removeClass("active");
        $(this).addClass("active");
        var p = $(this).parent();
        $('#popover').css('top', p.position().top + p.height() + 150).fadeToggle('fast');
    });


You can use event.stopPropogation so that event is not bubbled further. Maybe your function is being triggered from two different events and other one also get triggered while bubbling.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜