单击每个类项的函数

时间:2016-09-29 22:52:29

标签: javascript

我有一个课程hardware,点击后,我想在点击run功能时更改背景颜色。但是,我的点击会立即将它们全部设置为相同的颜色。

我如何区分每个hardware与各自的点击事件?

function run(){
var selector = document.getElementsByClassName('hardware');
for (var i = 0; i < selector.length; i++){
  var index = selector[i];
  selector[i].style.backgroundColor = "hotpink";
}

}
    <section onclick="run()" class="hardware">some text, nth-child is one</section>
    <section onclick="run()" class="hardware">some text, nth-child is two</section>
    <section onclick="run()" class="hardware">some text, nth-child is three</section>
    <section onclick="run()" class="hardware">some text, nth-child is four</section>
    <section onclick="run()" class="hardware">some text, nth-child is five</section>

3 个答案:

答案 0 :(得分:4)

只需使用run(this)将元素传递给函数,然后仅为该元素设置颜色:

function run(el){
  el.style.backgroundColor = "hotpink";

}
<section onclick="run(this)" class="hardware">some text, nth-child is one</section>
    <section onclick="run(this)" class="hardware">some text, nth-child is two</section>
    <section onclick="run(this)" class="hardware">some text, nth-child is three</section>
    <section onclick="run(this)" class="hardware">some text, nth-child is four</section>
    <section onclick="run(this)" class="hardware">some text, nth-child is five</section>

答案 1 :(得分:1)

试试这个:

function run(selector){
  selector.style.backgroundColor = "hotpink";
}

<section onclick="run(this)" class="hardware">some text, nth-child is one</section>

答案 2 :(得分:1)

另一种可能性:

function run(event){
  event.target.style.backgroundColor = "hotpink";
}
Array.prototype.forEach.call(
    document.getElementsByClassName("hardware"),
    function (el){
      el.onclick = run;
    }
);
<section class="hardware">some text, nth-child is one</section>
<section class="hardware">some text, nth-child is two</section>
<section class="hardware">some text, nth-child is three</section>
<section class="hardware">some text, nth-child is four</section>
<section class="hardware">some text, nth-child is five</section>