需要在表格中突出显示行

时间:2013-03-05 15:03:27

标签: javascript

我需要编写一个函数(或构建到下面的代码中),它将突出显示表中的特定行。它需要始终忽略表头,因此在表头之后开始行计数为0.

<style type="text/css">
#myTbl {
     border: 1px solid black
}
#myTbl td, th {
     border: 1px solid black
}

#myTbl tr.normal td {
    color: black;
    background-color: white;
}
#myTbl tr.highlighted td {
    color: white;
    background-color: gray;
}
</style>

  <table id="myTbl">
     <thead>
      <tr>
        <th>ID</th>
        <th>CreatedDate</th>
        <th>Name</th>
        <th>Colour</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>DFRF</td>
        <td>05/03/2010</td>
        <td>Lamp</td>
        <td>Blue</td>
      </tr>
Ect...  
    </tbody>
  </table>

<script type="text/javascript">
var table = document.getElementById("myTbl");
var thead = table.getElementsByTagName("thead")[0];
var tbody = table.getElementsByTagName("tbody")[0];

tbody.onclick = function (e) {
   e = e || window.event;
   var td = e.target || e.srcElement; 
//so must be no other elements inside the td
   var row = td.parentNode;
    alert('Row is ' + (row.rowIndex - 1))
   if (this.lst&&this.lst!=row){
    this.lst.className='';
   }
   row.className = row.className==="highlighted" ? "" : "highlighted";
   this.lst=row;
}

thead.onclick = function (e) {
   e = e || window.event;
   var th = e.target || e.srcElement;  
//so must be no other elements in the th
   alert(th.innerHTML);
}
</script>

这样的东西
function goToRow('2')

选择第2行。

需要帮助

1 个答案:

答案 0 :(得分:1)

您可以将计数添加为每个TR的ID。 见下文:

  <table id="myTbl">
     <thead>
      <tr id="tr0">
        <th>ID</th>
        <th>CreatedDate</th>
        <th>Name</th>
        <th>Colour</th>
      </tr>
    </thead>
    <tbody>
      <tr id="tr1">
        <td>DFRF</td>
        <td>05/03/2010</td>
        <td>Lamp</td>
        <td>Blue</td>
      </tr>

然后使用此JavaScript:

function goToRow(where)
{
 document.getElementById("tr"+where+"").style.color="white";
 document.getElementById("tr"+where+"").style.backgroundColor="gray";
}

希望有所帮助