2016-09-29 81 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)功能,然後設置只對元素的顏色:

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

試試這個:

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>