【问题标题】:adding a class to an element on click [duplicate]单击时向元素添加类[重复]
【发布时间】:2015-07-06 08:24:18
【问题描述】:

我想更改元素 onClick 的颜色 - 但是我已经有一个附加到 HTML 元素的 onCLick 函数。这是我的代码

function changeColor(cell){
    for (var i=0;i<cell.length;i++){
        cell[i].classList.remove("active")}
        elem.classList.add("active");
    }

}

table>
      <tr>
        <td><input  type="button"class= "input" id="cell1" onclick="clickThis(this.id)"></input></td>
        <td><input  type="button"class= "input" id="cell2" onclick="clickThis(this.id)"></input></td>
        <td><input  type="button"class= "input" id="cell3" onclick="clickThis(this.id)"></input></td>
      </tr> 
      <tr> 

【问题讨论】:

  • 对不起...你想做什么?
  • elem 来自哪里?
  • 试图在点击时改变按钮的颜色,对不起,不应该存在的元素应该是单元格

标签: javascript


【解决方案1】:

onclick 属性中可以有多个函数调用:

onclick="clickThis(this.id); changeColor(this);"

但是,将其包装成一个会更干净:

onclick="cellClick(this);"

function cellClick(cell){
   clickThis(cell.id);
   changeColor(cell);
}

如果你从 HTML 中抽象出来并使用event listeners,那就更好了。

【讨论】:

  • 恕我直言,在此处的答案中应积极避免使用整个 DOM0 onclick 内容 - 这是 1990 年代的 so。使用addEventListener 是唯一正确的答案。
【解决方案2】:

最好使用 addEventLister() 而不是使用内联处理程序......

但要使用内联处理程序,您可以

function clickThis(id) {
  snippet.log('clicked: ' + id)
};

function changeColor(cell) {
  var tr = cell.parentNode;
  for (var i = 0; i < tr.children.length; i++) {
    tr.children[i].classList.remove("active")
  }
  cell.classList.add("active");
}
.active {
  color: red;
  border: 1px solid green;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<table>
  <tr>
    <td>
      <input type="button" class="input" id="cell1" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell2" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell3" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" class="input" id="cell4" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell5" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell6" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
  </tr>
</table>
猜你喜欢
  • 2019-07-07
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2014-06-28
  • 2018-11-24
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多