javascript - 如何更改表格中点击的样式

标签 javascript html css

<分区>

我有一个 javascript,它使 HTML 中的表格可排序。但是我想设置使用 javascript 单击的列标题的样式。

如何获取表格的标题?我知道我需要更改的标题栏。

这是我的 javascript 现在返回给我的内容。

javascript

console.log(table.tHead);

输出到控制台:

<thead>
        <tr>
            <th>Name</th>
            <th>Times Placed</th>
            <th>UMF (KB)</th>
            <th>UAC</th>
            <th>Texture Memory (MB)</th>
            <th>Texture Count</th>
            <th>Mesh Memory (KB)</th>
            <th>Mesh Count</th>
            <th>Path</th>
        </tr>
</thead>

最佳答案

这会将 selected 类添加到点击的第 元素,并且会从之前点击的 元素中删除 selected 类>第:

document.querySelector('thead').addEventListener('click', function(e) {
  var current;
  if (e.target.tagName === 'TH') {
    current = document.querySelector('th.selected');
    if (current) {
      current.classList.remove('selected');
    }
    e.target.classList.add('selected');
  }
});
th {
  border: 1px solid #bbb;
  padding: 0.5em;
}
.selected {
  background: #def;
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Times Placed</th>
      <th>UMF (KB)</th>
      <th>UAC</th>
      <th>Texture Memory (MB)</th>
      <th>Texture Count</th>
      <th>Mesh Memory (KB)</th>
      <th>Mesh Count</th>
      <th>Path</th>
    </tr>
  </thead>
</table>

假设页面上只有一个表格,它应该可以与您现有的代码一起使用。

关于javascript - 如何更改表格中点击的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32702960/

上一篇:javascript - jQuery onclick 函数不会在嵌套的 div 上触发

下一篇:css - 带有 Bootstrap 的父导航栏内的全宽辅助导航栏

相关文章:

javascript - 在 Chrome 中显示 alert() 时 setTimeout() 过早触发

javascript - 使用 Jade 迭代嵌套数组对象

html - 仅将 CSS 水平下拉菜单中的顶部索引菜单项居中

html - 链接到具有相同名称的外部字体?

javascript - 传递给 createStore 的 preloadedState 参数具有意外类型 "Null"。预期参数是具有以下键的对象 : "login"

javascript - 用javascript react 显示相对时间

php - 如果启用了 javascript,则阻止 php 执行

html - 在 z-index 中将 div 层叠在一起的最佳方法是什么?

javascript - 相对于其底部定位 div

html - 如何在 LI 中为 DIV 设置 CSS 规则?