[英]Why does my function get called twice in 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张图像时,它只会被打印一次。 为什么是这样?
而不是在$('img[title*=\\"Show\\"]')
click函数中使用$(this)
$('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,这样事件就不会再冒泡了。 也许您的功能是由两个不同的事件触发的,而另一个事件在冒泡时也会被触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.