如果已单击已将表行颜色更改为白色

时间:2013-01-10 18:58:41

标签: javascript

如何修改以下代码以在现有代码之上添加功能,以便如果已经点击(黑色)相同的表行,并且随后再次单击该表,则将其从黑色更改为白?

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
tr.normal td {
    color: black;
    background-color: white;
}
tr.highlighted td {
    color: white;
    background-color: black;
}
</style>
</head>
<body>
<div id="results" class="scrollingdatagrid">
  <table id="mstrTable" cellspacing="0" border="1">
     <thead>
      <tr> 
        <th>File Number</th>
        <th>Date1</th>
        <th>Date2</th>
        <th>Status</th>
        <th>Num.</th>
      </tr>
    </thead>
    <tbody>
      <tr> 
        <td>KABC</td>
        <td>09/12/2002</td>
        <td>09/12/2002</td>
        <td>Submitted</td>
        <td>0</td>

      </tr>
      <tr> 
        <td>KCBS</td>
        <td>09/11/2002</td>
        <td>09/11/2002</td>
        <td>Lockdown</td>
        <td>2</td>
      </tr>

      <tr> 
        <td>WFLA</td>
        <td>09/11/2002</td>
        <td>09/11/2002</td>
        <td>Submitted</td>
        <td>1</td>
      </tr>
      <tr> 
        <td>WTSP</td>
        <td>09/15/2002</td>
        <td>09/15/2002</td>
        <td>In-Progress</td>
        <td>10</td>
      </tr>
    </tbody>
  </table>
</div>

<script type="text/javascript">
(
  function( )
  {
      var trows = document.getElementById("mstrTable").rows;

      for ( var t = 1; t < trows.length; ++t )
      {
          trow = trows[t];
          trow.className = "normal";
          trow.onclick = highlightRow;
      }

      function highlightRow( )
      {
          for ( var t = 1; t < trows.length; ++t )
          {
              trow = trows[t];
              trow.className = ( trow == this ) ? "highlighted" : "normal";
          }
      }
  }
)();
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

只需改变一下:

trow.className = ( trow == this ) ? "highlighted" : "normal";

对此:

trow.className = ( trow == this && trow.className != "highlighted") ? "highlighted" : "normal";

这是一个包含完整代码的jsFiddle:http://jsfiddle.net/uFrvN/

答案 1 :(得分:0)

这将删除所有类并仅设置所需的类。

function highlightRow( )
{
    for ( var t = 1; t < trows.length; ++t )
    {
        trow = trows[t];
        if(trow == this) {
            c = trow.className;
            trow.className = "";
            trow.className = ( c == "normal") ? "highlighted" : "normal";
            break;
        }
    }
}