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

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

Text Text Text

我希望使用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'); }); 

你有没有尝试过:

 $(this).closest('tr').find('td:not(:first-child)') 

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

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

使用下面的函数,您只需编写$(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) 
 $('input[type=checkbox]').click(function() { $(this).closest('td').siblings().find('select,input').hide(); }); 

我是stackoverflow的新手,我不确定我能否,但我编辑了@robjb的答案并在此发布。 完全归功于他。

如果有人想要只选择特定的堂兄弟而不是所有表兄弟(即想要选择器),那么我们可以使用@robjb答案的这个修改版本。 如果选择器不作为参数传递,那么它将给出所有表兄弟。

 (function($) { $.fn.cousins = function(selector) { var cousins; this.each(function() { var auntsAndUncles = $(this).parent().siblings(); auntsAndUncles.each(function() { if(cousins == null) { if(selector) cousins = auntsAndUncles.children(selector); else cousins = auntsAndUncles.children(); } else { if(selector) cousins.add( auntsAndUncles.children(selector) ); else cousins.add( auntsAndUncles.children() ); } }); }); return cousins; } })(jQuery) 

上述function的使用示例如下

 $(clickedObj).cousins('.singleWheel'); 

另一种选择是使用.filter()并使用@ robjb的答案。