[英].on event keeps getting fired over and over again
I'm trying to setup an event where it fires after my element is opened. 我正在尝试设置一个事件,在打开我的元素后触发该事件。 So I have a tooltip and I have a click event which shows the tooltip. 因此,我有一个工具提示,并且有一个显示该工具提示的click事件。 Then when that happens I setup a document click event that gets fired so if the user clicks anywhere on the stage it removes all tooltips. 然后,当发生这种情况时,我会设置一个文档单击事件,该事件会被触发,因此,如果用户在舞台上的任何位置单击,它将删除所有工具提示。 But what's happening is it gets called before the tooltip even gets a chance to show. 但是发生的事情是在工具提示甚至没有显示之前就调用了它。 So it's firing the document event over and over again. 因此,它反复触发文档事件。
$('.container img').popover({placement:'top', trigger:'manual', animation:true})
.click(function(evt){
evt.preventDefault();
el = $(this);
if(el.hasClass('active')){
el.popover('hide');
}else{
clearDocumentEvent();
el.popover('show');
$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(){
hideAllTooltips();
});
}
el.toggleClass('active');
})
var hideAllTooltips = function(){
$('.container img').popover('hide');
$('.container img').removeClass('active');
}
var clearDocumentEvent = function(){
$(document).off('click.tooltip touchstart.tooltip');
};
The problem stems from event bubbling. 问题源于事件冒泡。 You can verify this by doing the following test: 您可以通过执行以下测试来验证这一点:
$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(){
//hideAllTooltips();
console.log($(this)); // will return .container, body, html
});
Try using event.stopPropogation()
: 尝试使用event.stopPropogation()
:
$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(e){
e.stopPropagation();
hideAllTooltips();
});
DEMO: http://jsfiddle.net/dirtyd77/uPHk6/8/ 演示: http : //jsfiddle.net/dirtyd77/uPHk6/8/
Side note: I recommend removing .tooltip
from the on
function like 旁注:我建议从on
函数中删除.tooltip
$(document).on('click touchstart', ':not(.container img)', function(){
e.stopPropagation();
hideAllTooltips();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.