how to change the style of clicked th in table

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers

  • 这将一个添加selected类的点击th元素,它会删除所述selected从先前点击类th

    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>

    function makeMeBlue(element) {
      element.style.color = 'blue';
    }
    <table id="table">
      <thead>
        <tr>
          <th onclick="makeMeBlue(this)">Name</th>
          <th onclick="makeMeBlue(this)">Times Placed</th>
          <th onclick="makeMeBlue(this)">UMF (KB)</th>
          <th onclick="makeMeBlue(this)">UAC</th>
          <th onclick="makeMeBlue(this)">Texture Memory (MB)</th>
          <th onclick="makeMeBlue(this)">Texture Count</th>
          <th onclick="makeMeBlue(this)">Mesh Memory (KB)</th>
          <th onclick="makeMeBlue(this)">Mesh Count</th>
          <th onclick="makeMeBlue(this)">Path</th>
        </tr>
      </thead>
    </table>
    链接地址: http://www.djcxy.com/p/25224.html

    上一篇: 将参数添加到功能

    下一篇: 如何改变表格中点击的样式