4

我正在尝试使用 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 的跨度开始最近运行,我希望它返回它的父 td,因为它有一个标有兄弟匹配属性的兄弟。但是,如果我从标有 b 的跨度开始运行相同的命令,我希望它返回 table 标记,因为这是它找到的第一个父级,其兄弟级标记为 Siblingmatch 属性。

4

1 回答 1

3

你可以使用parentsfilter方法。

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

http://jsfiddle.net/WW5qL/

请注意,这siblingmatch不是一个有效的属性,您可以使用 HTML5data-*属性来代替。

于 2013-03-18T18:04:21.340 回答