使用jquery的close()来查找与已知兄弟元素最近的元素



我试图使用jquery最接近的命令来查找基于该元素是否有特定兄弟的特定元素。我一直在玩不同的选择器,但还没能找到一个我想要的。

例如,如果结构像下面这样

<div>
    <table>
        <tr>
            <td>
                  <span a>cell 1</span>
                  <span>cell 2</span>
            </td>
            <td siblingmatch="true">
                  <span b>cell 1</span>
                  <span>cell 2</span>
            </td>
        </tr>
    </table>
    <span siblingmatch="true">test 1</span>
</div>

如果我从标记为a的span开始运行,我希望它返回它的父td,因为它有一个标记为siblingmatch属性的兄弟。但是,如果从标记为b的span开始运行相同的命令,我希望它返回table标记,因为这是它找到的第一个带有标记为siblingmatch属性的兄弟节点的父节点。

您可以使用parentsfilter方法。

$('span').click(function(){
    var matched = $(this).parents().filter(function(){
         return $(this).siblings('[siblingmatch]').length;
    }).first();
});
http://jsfiddle.net/WW5qL/

注意,siblingmatch不是一个有效的属性,你可以使用HTML5 data-*属性代替。

最新更新