2011-10-01 120 views
1

我有以下的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。當我只有一個圖像時,它只會被打印一次。爲什麼是這樣?

回答

3

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

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

使用下面的代碼

$('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'); 
    }); 
0

您可以使用event.stopPropogation,這樣的事件不是進一步冒泡。也許你的功能是由兩個不同的事件觸發的,另一個也會在冒泡的時候被觸發。

相關問題