gpt4 book ai didi

jquery - 删除元素时未触发 Mouseleave

转载 作者:行者123 更新时间:2023-12-01 01:25:06 30 4
gpt4 key购买 nike

example fiddle

JavaScript

$('#btn').on('mouseover', function() {
$('#tt').show();
}).on('mouseleave', function() {
$('#tt').hide();
}).on('click', function() {
$(this).remove();
});

HTML

<button id="btn">press me</button>
<div id="tt">tooltip</div>

基本上,当您在光标仍在其上方时删除某个元素时,永远不会触发 mouseleave 事件。我想这是有道理的,因为如果元素消失了,事件/绑定(bind)也会消失。

但是我们如何解决这个问题呢?

当然,我也可以将 $('#tt').hide(); 放入 click 事件中,但我希望有一个更通用的解决方案。我的现实生活示例有点复杂,我并不总是知道元素何时会被删除。

没有 ondestroy 事件或任何我可以 Hook 的东西,它们会在被删除之前触发,是吗?

最佳答案

我已经更新了您的jsFiddle代码来自 this solution .

(function($){
$.event.special.destroyed = {
remove: function(o) {
if (o.handler) {
o.handler()
}
}
}
})(jQuery)

$('#btn').on('mouseover', function() {
$('#tt').show();
}).on('mouseleave', function() {
$('#tt').hide();
}).on('click', function() {
$(this).remove();
}).on('destroyed', function() {
$('#tt').hide();
})

或者,您可以绑定(bind)到 DOMNodeRemoved 突变事件,但 W3 spec声明此事件类型已弃用 due to performance and cross browser support issues .

$(document).bind('DOMNodeRemoved', function(e) {
if(e.target.id=='btn') {
$('#tt').hide();
}
});

在较新的浏览器(Chrome 18+、Firefox 14+)中,支持 MutationObserver对象,旨在替换突变事件。在你的情况下,它可以这样工作:

var target = document.querySelector('body');

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.removedNodes[0]!=undefined) {
if(mutation.removedNodes[0].id=='btn') {
$('#tt').hide();
}
}
});
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe(target, config);

这是一个link代码审查中的一个问题,其中有人正在编写 DOM MutationObserver shim,当 MutationObserver 对象不可用时,它会依赖于突变事件。

关于jquery - 删除元素时未触发 Mouseleave,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16050256/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com