Let me show you a demo: here
it is working for only rows. its not working for cells. i want to change cells' (tds') background colors with mouse clicks.
For example: a have a table, and it has 4 tds. table's background color is white. if i click to a td, a td should be red, than if i click to b, b td should be red and a td should be white again. if i click to c than, c should be red and b should be white right now.
A - B
C - D
Try updating the JavaScript to:
$( function() {
$('td').click( function() {
$(this).parents('table').find('td').each( function( index, element ) {
$(element).removeClass('on');
} );
$(this).addClass('on');
} );
} );
Instead of having the line:
$(this).addClass("on").parent().siblings("tr").find("td").removeClass("on");
you could just store which is the colored cell and remove the class without having to search, like this:
var light = null;
$(function(){
$("td").click(function(){
if(light) { light.removeClass("on"); }
light = $(this);
light.addClass("on");
});
});
HTML: add a class to the table:
<table class="color_changing">...</table>
jQuery:
$('table.color_changing tr td').live('click', function(){
$(this).parent().parent().each('td', function(){
$(this).removeClass('red');
});
$(this).addClass('red');
});
should work!
How about if you do this?
<script>$(function(){
$("td").click(function(){
$(this).addClass("on").siblings().removeClass("on");
});
});</script>
It will do the same effect with the other TD cells in the same row. Or do you want a cell lighting up to turn off all other cells on the table, no matter the row?
来源:https://stackoverflow.com/questions/4543101/jquery-onclick-change-background-color-for-table-cells