考虑以下HTML。如果我有一个JSON参考<按钮>元件,我怎样才能在这两种情况下得到外元素的引用

<table id="my-table">
    <tr>
        <td>
            <button>Foo</button>
        </td>
        <td>
            <div>
                <button>Bar</button>
            </div>
        </td>
    </tr>
</table>

<script type="text/js">
    $('#table button').click(function(){
        //$(this).parent().parent() will work for the first row
        //$(this).parent().parent().parent() will work for the second row
        //is there a selector or some magic json one liner that will climb
        //the DOM tree until it hits a TR, or do I have to code this myself
        //each time?            
        //$(this).????
    });
</script>

我知道我可以特殊情况下,每个条件,但我更感兴趣“然而深,你碰巧是,爬上树,直到找到元素X”式的解决方案。这样的事情,但更jQuery的喜欢/不那么详细

var climb = function(node, str_rule){
    if($(node).is(str_rule)){
        return node;
    }
    else if($(node).is('body')){
        return false;
    }
    else{
        return climb(node.parentNode, str_rule);
    }
};  

我知道父(表达式)方法,但是从我所看到的是,您可以过滤父母一个级别并不会爬的树,直到找到EXPR(我喜欢的代码示例,证明我是错的)

有帮助吗?

解决方案

父母功能你想要做什么:

$(this).parents("tr:first");

其他提示

此外,如果正在使用jQuery 1.3+可以使用最接近方法

$(this).closest("tr");

没有的jQuery但这种选项的效果要好得多。

node.contains(otherNode)

  

在Node.contains()方法返回一个布尔值指示是否   一个节点是一个给定节点的后代或不

https://developer.mozilla.org/en/docs /网络/ API /节点/包含

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top