Javascript 为什么我的函数在jQuery中被调用了两次?
我有以下jQueryJavascript 为什么我的函数在jQuery中被调用了两次?,javascript,jquery,Javascript,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().heig
$('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');
}
});
我有两张标题为“显示选项”的图片。出于某种原因,每当我点击其中任何一张图片时,它都会被打印两次。当我只有一个图像时,它只打印一次。这是为什么?而不是$('img[title*=“Show\”])
内部单击函数使用$(此)
如果不起作用,请使用:
$('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,这样事件就不会进一步冒泡。可能您的函数是由两个不同的事件触发的,而另一个在冒泡时也会触发