2013-03-05 35 views
-1

我需要編寫一個函數(或構建到下面的代碼上)來突出顯示錶中的特定行。它需要始終忽略表頭,因此在表頭之後開始行計數爲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行。

需要幫助,請

+0

有很多網站在那裏,教你如何做到這一點的。像這樣一個:http://www.netmechanic.com/news/vol4/javascript_no20.htm 這個答案也可能是有用的:http://stackoverflow.com/questions/5661070/highlight-table-row?rq=1 – 2013-03-05 15:06:59

回答

1

您可以添加的數量作爲ID對每個TR。 見下圖:

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

希望幫助

+0

很簡單,但沒有想到。謝謝 – 2013-03-05 15:09:52