2016-09-29 1 views
1

私はクラス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>

答えて

4

ちょうどrun(this)を使用して関数に要素を渡し、その後、唯一のその要素の色を設定

1

これを試してみてください:

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>

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

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