为什么我的函数在jQuery中被调用两次?

问题描述:

我有以下的jQuery为什么我的函数在jQuery中被调用两次?

$('img[title*=\"Show\"]').click(function() { 
     //$e.preventDefault();  
     var position = $('img[title*=\"Show\"]').parent().position(); 
     $('#popover').css('top', position.top + $('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'); 
     } 
     }); 

我有标题两个图像“显示选项”。出于某种原因,每当我点击任何这些图像时,它都会被打印TWICE。当我只有一个图像时,它只会被打印一次。为什么是这样?

,而不是$('img[title*=\"Show\"]')点击功能使用内部$(this)
如果不使用的作品:

$('img[title*=\"Show\"]').click(function(e) { 
     e.stopImmediatePropagation(); 
     //other 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'); 
    }); 

您可以使用event.stopPropogation,这样的事件不是进一步冒泡。也许你的功能是由两个不同的事件触发的,另一个也会在冒泡的时候被触发。