简体   繁体   中英

javascript toggle table row background color on click

So i have some javascript code which on a table row click exapnds all subsequent table rows until it finds the same table row class again.

If you hover over a row it changes to gray which is what i expected.

The only stuff that doesn't work is when you click on the table row, i want the table row background color to be same as the hover (gray). the color should disappear when you click back and collapse the row.

I tried to add a toggle class as seen below.

$('.my-class').click(function(){

    $(this).nextUntil('tr.my-class').slideToggle(100);
    $(this).toggleClass("tr.my-class.negative.clicked");
});

But I am not sure if that is the right approach. Here is my jsfiddle: http://jsfiddle.net/DhdRG/3/

Just an heads up. This worked too and this might be a better solution:

$('.my-class').click(function(){

    $(this).nextUntil('tr.my-class').slideToggle(100);
    $(this).toggleClass("clicked");

});

http://jsfiddle.net/DhdRG/7/

You can toggle the class with the same event

DEMO http://jsfiddle.net/kevinPHPkevin/DhdRG/4/

$('.composite-test').toggleClass("grey");

You could try $(this).removeClass('tr.my-class').addClass('tr.my-class.negative.clicked'); instead of $(this).toggleClass('tr.my-class.negative.clicked') But replace $(this) with the clicked tr's id.

You can toggle another CSS class to have the table row background color to be same as the hover (gray). http://jsfiddle.net/DhdRG/5/

$('.my-class').click(function(){

    $(this).nextUntil('tr.my-class').slideToggle(100);
    $(this).toggleClass("tr.my-class.negative.clicked");
    $(this).toggleClass("rowBg"); // added this line
});

CSS

.rowBg { background:gray;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM