2011-10-01 4 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'); 
     } 
     }); 

내가 제목을 가진 두 개의 이미지가 있습니다 "옵션 표시를." 어떤 이유로이 이미지 중 하나를 클릭 할 때마다 두 번 인쇄됩니다. 이미지가 1 개인 경우 한 번만 인쇄됩니다. 왜 이런거야? 하지 않는 경우

답변

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'); 
    }); 
해당 이벤트가 아닌 있도록 event.stopPropogation을 사용할 수 있습니다
0

더 버블 링했다. 어쩌면 당신의 기능은 두 개의 다른 이벤트에서 트리거되고 다른 트리거는 버블 링되는 동안 트리거됩니다.

관련 문제