JQuery如何选择表格单元格并设置边框并取消选择前一个单元格

时间:2015-02-12 13:16:28

标签: jquery html-table

基于以下两个例子: jQuery: Change the border color of ONE table cell& Getting td by index with jQuery;

我尝试选择表格单元格,然后取消选择前一个,但结果是 我只选择了单元而没有取消它。

 var prevCol = -1;
     var prevRow = -1;
     $("#tbl_menu").on("click", "td" ,function () {
         var col = $(this).parent().children().index($(this));
          var row = $(this).parent().parent().children().index($(this).parent());

          //alert('Row: ' + row + ', Column: ' + col);
          $(this).toggleClass('selected');
           console.log("col"+col );
            console.log("prevCol"+prevCol );
          if(prevCol>-1)
          {
            console.log("ssss");
            var c = $('#tbl_menu tr').eq(prevRow).find('td').eq(prevCol).toggleClass('selectedOut');
            c.toggleClass('selectedOut');
          }
          prevCol = col;
          prevRow = row;
     });

和表格:

<table  id="tbl_menu" border="1" width="180px" >
 <tr>
    <td bgcolor="#FF6500">&nbsp;</td>
    <td bgcolor="#F4D7D7">&nbsp; </td>
    <td bgcolor="#F4D7D7">Coin</td>
    <td bgcolor="#F4D7D7">Gate</td>
    <td bgcolor="#F4D7D7">Coin Wall</td>
    <td >&nbsp; </td>
    <td >&nbsp; </td>
    <td >&nbsp; </td>

</tr>
</table>

和样式

<style>
table{
    border: 1px solid black;
    table-layout: fixed;
    width: 180px;
}

th, td {
    border: 1px solid black;
    overflow: hidden;
    width: 30px;
    hight: 30px;
}

td.selected { border: 3px solid #F00; }
td.selectedOut { border: 3px solid #F22; }
</style>

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

你有简单易用的事情

$(document).ready(function() {
    $("#tbl_menu").on("click", "td", function() {
        $("#tbl_menu td.selected").removeClass('selected'); //Remove previous selected 
        $(this).addClass('selected'); //Add class to current cell
    });
});

&#13;
&#13;
    $(document).ready(function() {
        $("#tbl_menu").on("click", "td", function() {
            $("#tbl_menu td.selected").removeClass('selected');
            $(this).addClass('selected');
        });
    });
&#13;
table {
  border: 1px solid black;
  table-layout: fixed;
  width: 180px;
}
th,
td {
  border: 1px solid black;
  overflow: hidden;
  width: 30px;
  hight: 30px;
}
td.selected {
  border: 3px solid #F00;
}
td.selectedOut {
  border: 3px solid #F22;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl_menu" border="1" width="180px">
  <tr>
    <td bgcolor="#FF6500">&nbsp;</td>
    <td bgcolor="#F4D7D7">&nbsp;</td>
    <td bgcolor="#F4D7D7">Coin</td>
    <td bgcolor="#F4D7D7">Gate</td>
    <td bgcolor="#F4D7D7">Coin Wall</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>

  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

 $("#tbl_menu").on("click", "td" ,function () {
     $(this).siblings().removeClass('selected');
      $(this).addClass('selected');

 });

Working Demo