1

I'm trying to highlight the parent tr of a table, if a children td > p has a certain class. I have the following:

$(document).ready(function(){
    var $target = $('.flag-wrapper p').closest("tr");
    var $element = $('.flag-wrapper p').hasClass("selector-on");

    if ( $element ) {
        $target.addClass("marked-row");
    } else {
        // whatsoever
    }
});

http://jsfiddle.net/cZJca/1/

Now my problem is that I can't target just the current tr. I've tried using $(this) but as far as I can tell it won't work inside the if statement.

Any insights on how should I proceed with this would be much appreciated. Also, I guess it would be easier to work with a .click() event but I have to check this .hasClass() on page load instead of user action.

4

5 回答 5

6

Just use:

 $('.flag-wrapper p.selector-on').closest('tr').addClass("marked-row");

This finds all p elements inside .flag-wrapper that have the class .selector-on. It then gets the closest tr of each of the matches and adds the .marked-row class.

Here it is working: http://jsfiddle.net/cZJca/6/

于 2013-07-09T14:36:37.020 回答
1

Loop over each one and deal with it separately.

$('.flag-wrapper p').each(function(){
    var $this = $(this);
    var $target = $this.closest("tr");

    if($this.hasClass("selector-on")){
        $target.addClass("marked-row");
    } else {
        // whatsoever
    }
});
于 2013-07-09T14:36:59.597 回答
0

You just need to do

$('tr:has(.flag-wrapper p.selector-on)').addClass('marked-row');

FIDDLE

or

$('tr').has('.flag-wrapper p.selector-on').addClass('marked-row');

FIDDLE

于 2013-07-09T14:36:08.163 回答
0

You can loop over the paragraphs to target them individually:

$(document).ready(function(){
    $('.flag-wrapper p').each(function() {
        var $curElement = $(this);
        if ($curElement).hasClass("selector-on")) {
            $curElement.closest("tr").addClass("marked-row");
        } else {
           // whatsoever
        }
    });
});
于 2013-07-09T14:37:26.010 回答
0
$('.flag-wrapper p.selector-on').closest('tr').addClass('marked-row');
于 2013-07-09T14:39:22.800 回答