代码之家  ›  专栏  ›  技术社区  ›  Alana Storm

是否有jquery选择器/方法来查找特定的父元素n级别?

  •  48
  • Alana Storm  · 技术社区  · 16 年前

    考虑下面的HTML。如果我有一个对<button>元素的JSON引用,在这两种情况下,如何获取对外部<tr>元素的引用?

    <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);
        }
    };  
    

    我知道parent(expr)方法,但我看到的是允许你过滤一级的父级,直到找到expr才爬树(我喜欢代码示例证明我错了)

    3 回复  |  直到 16 年前
        1
  •  92
  •   Paolo Bergantino    16 年前

    这个 parents 函数执行您想要的操作:

    $(this).parents("tr:first");
    
        2
  •  43
  •   bendewey    16 年前

    此外,如果您使用的是jquery 1.3+,则可以使用 closest 方法

    $(this).closest("tr");
    
        3
  •  0
  •   zloctb    8 年前

    不是jquery,但是这个选项工作得更好

    node.contains(其他节点)

    node.contains()方法返回一个布尔值,该值指示 节点是否为给定节点的后代

    https://developer.mozilla.org/en/docs/Web/API/Node/contains