使用jQuery显示隐藏的行nearest()到选中

时间:2015-06-10 16:23:08

标签: javascript jquery

我是jQuery的新手,但是当用户选择上面的(可见)时,我正试图显示最近的隐藏表格行。

HTML

 Click on a row for more info:
<table>
    <tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
    <tr class="child"><td><p>Blah blah blah.</p>
    </td></tr>

    <tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
    <tr class="child"><td><p>Blah blah blah.</p>
    </td></tr>

    <tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
    <tr class="child"><td><p>Blah blah blah.</p>
    </td></tr>    
</table>

的jQuery

$(function() {
    $("tr.child").hide();

    $("table").click(function(event) {
        event.stopPropagation();

        var $target = $(event.target);
        $target.closest("tr.child").toggle();
    });
});

这是fiddle。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

.closest()遍历祖先的DOM结构。

使用给定的表结构,应使用.next()

切换下一个tr

你可以做这样的事情

$("table tr").click(function(event) {
    $(this).next(".child").toggle();
});

这是一个演示 https://jsfiddle.net/dhirajbodicherla/mfwYS/1166/

答案 1 :(得分:1)

你拥有的是好的。您需要首先使用<tr>函数找到最接近的closest()元素。

然后使用nextAll()函数在该元素之后查找所有以下.child类,但只选择第一个返回的

$("table").click(function(event) {
    event.stopPropagation();

    var $target = $(event.target);
    $target.closest("tr").nextAll('.child').first().toggle();
});

看到这个小提琴

https://jsfiddle.net/mfwYS/1165/