假设您设置了 var $this = jQuery(this);
如何在 dom 中搜索该元素。 $this.size()
不起作用,因为它没有在 dom 中搜索该元素。我基本上需要检测 $this 是否已从 dom 中删除并停止一个间隔。
请求更新代码:
jQuery(document).find('div.ctalk').each(function(){
var delay;
var $this = this;
activateLive = function($this) {
clearInterval(delay);
delay = setInterval(function(){
if(jQuery($this).size() != '0') {
fn.actJSON('0', $this, 'update=1&');
}else {
alert('kill it');
clearInterval(delay);
}
}, 10000 );
}
if(!jQuery(this).data('init')) {
jQuery(this).data('init', '1');
fn.activateBinds($this);
activateLive($this);
}
});
最佳答案
这可能是我第一次提倡使用 .is()
对于任何事情,但这确实使这成为一项非常简单的任务:
if (!$(this).parents().is("body")) {
// Node has been disconnected
}
如果您想检查文档中任何位置的节点,可以将“body”
替换为“html”
。
IE 还有一个专有的 sourceIndex
可以以稍微更好的性能完成工作的属性:
if (this.sourceIndex == -1 || !$(this).parents().is("body")) {
// Node has been disconnected
}
<小时/>
额外更新:我知道还有一些其他方法可以实现这一点,它们在我脑海中浮现,但我不太记得了。现代浏览器有 DOM Level 3 方法 .compareDocumentPosition()
,所以如果有人需要的话,你可以在没有 jQuery 的情况下完成整个事情。
if (this.sourceIndex == -1 || document.compareDocumentPosition(this) & 0x01) {
// Node has been disconnected
}
我想到的另一种方法是IE的.contains()
方法,也有效。但是,使用它需要首先检查函数是否已定义,这样更容易坚持使用 sourceIndex
。
关于jQuery 在 dom 中找到这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259812/