如何在java脚本

时间:2018-05-15 16:18:00

标签: javascript html css

如何使用HTML中的内联Javascript更改选定的表格行颜色我正在尝试这种方式

的onclick =" this.style.backgroundColor ='蓝色'" 我在

中写这篇文章



<tr onclick="this.style.backgroundColor='blue'">
   <td>row1</td>
   <td>row2</td>
</tr>
&#13;
&#13;
&#13;

当我点击row1时,行颜色应该变为蓝色。当我再次点击row2然后row1背景颜色重置为正常而row2背景颜色变为蓝色我该如何实现。

2 个答案:

答案 0 :(得分:1)

如果你真的需要一个单行的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>

答案 1 :(得分:0)

你不能使用内联javascript。

我会使用类似的东西( for modern browsers

// 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>