简体   繁体   English

jQuery找到哪个父亲更近?

[英]jQuery find which parent is closer?

In jQuery you can call closest to find the closest parent. 在jQuery中,您可以调用closest的查找最近的父级。

If I have a a in a li in a ul in a td in a table . 如果我有aliultdtable I want to find out if the ul parent is closer than the table parent. 我想知道ul父级是否比table父级更接近。 Obviously in this case the answer is obvious. 显然,在这种情况下答案是显而易见的。

If I run $('a').closest('table').length or $('a').closest('ul').length both return 1. 如果我运行$('a').closest('table').length$('a').closest('ul').length都返回1。

I would like to find out which parent is closer in the DOM. 我想找出哪个父级在DOM中更接近。

Technically if there were a method than in this case $('a').closer('ul', 'table') would return the ul because it is closer in the DOM. 从技术上讲,如果有一种方法比在这种情况下$('a').closer('ul', 'table')将返回ul因为它在DOM中更接近。

<table> <!-- Is this closer -->
    <tr>
        <td>
            <ul> <!-- Or is this closer -->
                <li>
                    <a href="#">A button</a>
                </li>
            </ul>
        </td>
    </tr>
</table>

You can list multiple element selectors to the closest function, it will only find the closest of one of them: 您可以列出closest函数的多个元素选择器,它只会找到最接近的一个:

$('a').closest('table, ul')

Example: 例:

 $(document).on("click", function( event ) { $(event.target).closest("li, b").toggleClass("hilight"); }); 
 .hilight{ background: rgba(255, 0, 0, 0.5); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><b>Click me!</b></li> <li>You can also click this line <b>or click me!</b></li> </ul> 

Use .parents() . 使用 .parents() It returns a list of all parents that are ordered from closest to farthest. 它返回从最近到最远订购的所有父母的列表。

The difference between using this and using .closest(selector) is that it accepts a jQuery object instead of a selector string, which has to be hard coded. 使用它和使用.closest(selector)之间的区别在于它接受jQuery对象而不是选择器字符串,它必须是硬编码的。 Meanwhile jQuery objects can be collections and so can be generated on the fly. 同时jQuery对象可以是集合,因此可以动态生成。

(function($) {
  $.fn.getClosest = function(testElements) {
    var element = $(this);
    var parents = element.parents();
    var indexClosest = Number.MAX_VALUE;
    testElements.each(function() {
      var index = parents.index($(this));
      if (index > -1 && index < indexClosest)
        indexClosest = index;
    });
    return parents.eq(indexClosest);
  };
})(jQuery);

Use the function like this: 使用这样的功能:

$("a").getClosest($("table, ul"))

Fiddle with advanced use case 摆弄高级用例

I like Fabian's answer; 我喜欢法比安的回答; but to actually measure the distance, you can use this: 但要实际测量距离,您可以使用:

 var $parentsUntilTable = $('li').parentsUntil('table'); var $parentsUntilUl = $('li').parentsUntil('ul'); console.log($parentsUntilTable.length < $parentsUntilUl.length ? 'table is closer' : 'ul is closer'); 
 <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <ul> <li> </li> </ul> </td> </tr> </table> 

Here is a simple implementation of the .closer() method that returns the selector that is closest to the given element: 这是一个简单的.closer()方法实现,它返回最接近给定元素的选择器:

$.fn.closer = function(varargs) {
  var $elem = $(this);
  while ($elem.length) {
    for (var i = 0, len = arguments.length; i < len; i++) {
      if ($elem.is(arguments[i])) {
        return arguments[i];
      }
    }
    $elem = $elem.parent();
  }
  return null;
};

See it in action on jsFiddle . 在jsFiddle中查看它的实际操作。

An element only has one parent node, above those are ancestor nodes. 元素只有一个父节点,其上面是祖先节点。

From here: https://stackoverflow.com/a/15149590/1876047 - you can use 从这里: https//stackoverflow.com/a/15149590/1876047 - 你可以使用

$(elem1).offset().top - $(elem2).offset.().top

As both nodes are ancestors of the element you are considering, the one furthest from the root of the DOM tree is the closet to your element. 由于两个节点都是您正在考虑的元素的祖先,因此距离DOM树根最远的节点是元素的壁橱。

So if the above difference is greater than 0, then elem2 is closest, otherwise elem1 is closest. 因此,如果上述差值大于0,则elem2最接近,否则elem1最接近。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM