如何使用JQuery获取堂兄元素?

Bar*_*rry 14 javascript jquery

我有一个包含许多行数据的表,我想根据第一个元素中的复选框显示或隐藏每行的一些细节.例如:

<table>
  <tr>
    <td><span class="aspnetweirdness"><input type=checkbox></span></td>
    <td>Text Text Text</td>
    <td><select /></td>
    <td><input type=text></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我希望使用jquery从复选框遍历表达元素(文本,选择和文本输入),并根据是否选中复选框切换这些元素的可见性.一个小障碍是复选框包含在一个范围内,因为这是由asp.net输出的.这也使得元素更难以通过id获取.

我该怎么做呢?我已经尝试了$(this).parentsUntil('tr').siblings(),但它似乎并没有得到正确的元素.

任何帮助,将不胜感激.

编辑:

 $(".crewMemberTable input:checkbox").toggle(function() {
            $(this).closest('tr').find('select, input:not(:checkbox)').fadeIn();
            $(this).closest('tr').find('label').css('font-weight', 'bold');
        }, function() {
            $(this).closest('tr').find('select, input:not(:checkbox)').fadeOut();
            $(this).closest('tr').find('label').css('font-weight', 'normal');
        });
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 19

你有没有尝试过:

$(this).closest('tr').find('td:not(:first-child)')
Run Code Online (Sandbox Code Playgroud)

如果代码在"点击"处理程序或其他东西,"this"将是你的复选框元素.


Rob*_*Rob 5

我知道这是一个老问题,但我偶然发现它并意识到我最近为此编写了一个通用函数.

使用下面的函数,您可以简单地编写$(this).cousins()以获取包含text,select和text-input元素的集合(this当然,这是您的复选框.)

/* See http://addictedtonew.com/archives/414/creating-a-jquery-plugin-from-scratch/
 * Used like any other jQuery function:
 *        $( selector ).cousins()
 */
(function($) {
    $.fn.cousins = function() {
        var cousins;
        this.each(function() {
            var auntsAndUncles = $(this).parent().siblings();
            auntsAndUncles.each(function() {
                if(cousins == null) {
                    cousins = auntsAndUncles.children();
                }
                else cousins.add( auntsAndUncles.children() );
            });
        });
        return cousins;
    }
})(jQuery)
Run Code Online (Sandbox Code Playgroud)

  • 我不同意 - 字典或维基百科也不同意:http://en.wikipedia.org/wiki/Ancestor http://dictionary.reference.com/browse/ancestor 但我想你可以在英语上问另一个观点。但是,我仍然喜欢您的回答,所以无论如何我都给了您赞成票:) (2认同)