我如何选择一系列包含所有这些元素的元素的第一个父代?
例如:
<body> <dl> <dt>Items:</dt> <dd> <ul> <li>Item 1<div class="item-info">...</div></li> <li>Item 2<div class="item-info">...</div></li> <li>Item 3<div class="item-info">...</div></li> </ul> </dd> </dl> </body>
我想要这样的东西:
$('.item-info').commonParent();
它将返回相当于:
[$('ul')]
解决方法
如果你真的是寻找最低的共同祖先(
See this working in a fiddle):
jQuery.fn.commonAncestor = function() { var parents = []; var minlen = Infinity; $(this).each(function() { var curparents = $(this).parents(); parents.push(curparents); minlen = Math.min(minlen,curparents.length); }); for (var i in parents) { parents[i] = parents[i].slice(parents[i].length - minlen); } // Iterate until equality is found for (var i = 0; i < parents[0].length; i++) { var equal = true; for (var j in parents) { if (parents[j][i] != parents[0][i]) { equal = false; break; } } if (equal) return $(parents[0][i]); } return $([]); }
例
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script src="jquery.commonancestor.js"></script> $(function() { console.log($(".item-info").commonAncestor()); }); </script> <body> <dl> <dt>Items:</dt> <dd> <ul> <li>Item 1<b><div class="item-info">...</div></b></li> <li>Item 2<u><div class="item-info">...</div></u></li> <li>Item 3<i><div class="item-info">...</div></i></li> </ul> </dd> </dl> </body>
这并没有经过严格的测试,所以请指出你看到的任何错误.
编辑返回父代替$(父)
EDIT在IE8中不工作