How do I get to cousin elements with JQuery?

前端 未结 4 1235
抹茶落季
抹茶落季 2020-12-31 04:35

I have a table with many rows of data, and I want to show or hide some of the details on each row based on a checkbox in the first element. For example:

<         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 04:45

    I am new to stackoverflow and I'm not sure if I can or not, but I edited the answer of @robjb and posting here. Full credit goes to him only.

    In case if anyone wants to select only particular cousins and not all cousins (i.e. wants to have selector), then we can use this modified version of @robjb 's answer. If selector is not passed as an argument then it will give all cousins.

    (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)
    

    Example use of the above function would be as

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

    The other option would be to use .filter() and use @robjb's answer.

提交回复
热议问题