![](/img/trans.png)
[英]How to change background color of a table cell in java script using row and column number?
[英]How to change the table row color onclick function in java script
如何使用HTML中的內聯Javascript更改選定的表格行顏色
onclick =“ this.style.backgroundColor ='blue'”我正在寫這個
<tr onclick="this.style.backgroundColor='blue'"> <td>row1</td> <td>row2</td> </tr>
當我單擊第1行時,行顏色應更改為藍色。當我再次單擊第2行時,行1的背景色將重置為普通色,而行2的背景色將變為藍色如何實現此目的。
如果您確實需要單行js,那么(對於現代瀏覽器):
.selected { background-color: coral; } table { border-spacing:0; }
<table> <tr onclick="var s = this.parentNode.querySelector('tr.selected'); s && s.classList.remove('selected'); this.classList.add('selected');"> <td>row1</td> <td>row2</td> </tr> <tr onclick="var s = this.parentNode.querySelector('tr.selected'); s && s.classList.remove('selected'); this.classList.add('selected');"> <td>row1</td> <td>row2</td> </tr> </table>
您不能使用內聯JavaScript來做到這一點。
我會用這樣的東西( 對於現代瀏覽器 )
// delegate the event handling to the table document.querySelector('table').addEventListener('click', function(e) { var closestCell = e.target.closest('td'), // identify the closest td when the click occured activeCell = e.currentTarget.querySelector('td.selected'); // identify the already selected td closestCell.classList.add('selected'); // add the "selected" class to the clicked td if (activeCell) activeCell.classList.remove('selected'); // remove the "selected" class from the previously selected td })
.selected { background: blue; color: white; }
<table> <tr> <td>row1</td> <td>row2</td> </tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.