【问题标题】:How to change the table row color onclick function in java script如何在javascript中更改表格行颜色onclick函数
【发布时间】:2018-10-25 13:34:39
【问题描述】:

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

onclick="this.style.backgroundColor='blue'" 我正在写这篇文章

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

当我单击 row1 时,该行颜色应变为蓝色。当我再次单击 row2 时,row1 背景颜色重置为正常,row2 背景颜色变为蓝色我怎样才能做到这一点。

【问题讨论】:

  • 您需要了解文本 row1row2 在同一表格行中。 td 代表单元格而不是行(tr 表示)。
  • 行是动态的,所以我不能在 td 上写它
  • 我明白,但您的示例代码显示 2 个单元格而不是 2 行。
  • 切换课程要容易得多

标签: javascript html css


【解决方案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>

【讨论】:

  • 完美答案。预期同样的结果。谢谢
【解决方案2】:

你不能使用内联 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>

【讨论】:

  • 这很好,但是我在表格是一个组件的角度做的,所以我不能在那个页面中粘贴 java 脚本代码:( 所以需要单行代码或任何其他方式来实现这个跨度>
  • @ShreenivasKulkarni 然后发布您的角度代码并使用角度标签标记您的问题。
猜你喜欢
  • 2011-05-23
  • 2017-06-19
  • 2020-05-17
  • 2014-02-11
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
相关资源
最近更新 更多