jQuery 在 dom 中找到这个

标签 jquery find this

假设您设置了 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/

相关文章:

javascript - 如何使用jquery在子菜单下动态添加子菜单?

javascript - 获取父元素以外的元素的偏移量?

java - MongoDB 数字范围搜索无法按预期工作

shell - 如何从查找 "type d"中排除此/当前/点文件夹

javascript - 显示所选名称的数据库值并将该名称插入另一个表

javascript - 如何确保特定的单击事件处理程序在所有其他附加的单击处理程序之后执行?

regex - 在 Notepad++ 中查找和替换

c++ - 在 C++ 中返回 "this"?

javascript - 失去 `this` 关键字的显式绑定(bind)

null - 如何将 Redux Saga 与 AWS Amplify 结合使用?