Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中定位单击事件_Javascript - Fatal编程技术网

如何在javascript中定位单击事件

如何在javascript中定位单击事件,javascript,Javascript,如何将click事件作为目标,以便在不同的div中重用.js框,而不影响其他div容器 var box = document.querySelector('.js-box'), colors = ['green', 'blue', 'red']; box.onclick = function() { color = colors.shift(); colors.push(color); box.className = 'js-box' + ' ' + colo

如何将click事件作为目标,以便在不同的div中重用.js框,而不影响其他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”,但我似乎能理解它


文档。querySelector
仅选择第一个元素,而不是全部

这就是为什么需要
document.getElementsByClassName

var-box=document.getElementsByClassName('js-box'),
颜色=[‘绿色’、‘蓝色’、‘红色’];
对于(变量i=0;i
.js盒{
宽度:200px;
高度:200px;
利润率:50像素;
边框:薄灰色实心;
显示:块;
}
瑞德先生{
背景色:红色;
}
蓝先生{
背景颜色:蓝色;
}
格林先生{
背景颜色:绿色;
}


使用
this.className
而不是
box.className
。另外,是的,您需要使用
getElementsByClassName
而不是
querySelector
或者,您可以使用
querySelectorAll