jQuery - OnClick, change background color for table cells

二次信任 提交于 2019-12-06 09:24:06

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

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?

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