简体   繁体   中英

how to target click event in javascript

How can I target the click event so that I can reuse the .js-box in different divs without effecting the other div containers?

var box = document.querySelector('.js-box'),
    colors = ['green', 'blue', 'red'];

box.onclick = function() {
    color = colors.shift();
    colors.push(color);

    box.className = 'js-box' + ' ' + color;
};

I'm quite sure my solution is to do with the correct use of 'this' but i can seem to get my head around it

http://jsfiddle.net/Grundizer/ky1tb3r5/

document.querySelector only selects the first element, not all!

Thats why you need document.getElementsByClassName

 var boxes = document.getElementsByClassName('js-box'), colors = ['green', 'blue', 'red']; for (var i = 0; i < boxes.length; i++) { boxes[i].onclick = function() { color = colors.shift(); colors.push(color); this.className = 'js-box' + ' ' + color; }; } 
 .js-box { width:200px; height:200px; margin:50px; border:thin grey solid; display:block; } .red { background-color:red; } .blue { background-color:blue; } .green { background-color:green; } 
 <div class="js-box"></div> <div class="js-box"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM