繁体   English   中英

如何在javascript中定位点击事件

[英]how to target click event in javascript

如何定位click事件以便我可以在不同的div中重用.js-box而不影响其他div容器?

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

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

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

我很确定我的解决方案是正确使用'this',但我似乎能够理解它

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

document.querySelector只选择第一个元素,而不是全部!

这就是为什么你需要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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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