jQuery - OnClick, change background color for table cells

天大地大妈咪最大 提交于 2019-12-07 23:41:44

问题


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


回答1:


Try updating the JavaScript to:

$( function() {
  $('td').click( function() {
    $(this).parents('table').find('td').each( function( index, element ) {
        $(element).removeClass('on');
    } );
    $(this).addClass('on');
  } );
} );

Preview




回答2:


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");
  });
});



回答3:


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!




回答4:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!