2016-09-29 62 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>