好吧,我不得不重新措辞以更好地理解我的问题。
所以我有一个充满 div 的 block ,我想让它们在单击时改变颜色。因此,如果我对 this 使用内联引用,该函数将正常工作。
<html><head><style>
body {font-family:"BACKTO1982", System, san serif; background-color:#666; font-weight: normal; font-size: normal; padding: 0; margin: 0; height: 100%; min-height: 700px; width: 100%; min-width: 800px; overflow: hidden;}
#theBlock {position:relative; height: 640px; width: 800px; margin:20px auto 20px auto; padding:0; overflow:hidden;}
.blocks {height:12px;width:12px;border:1px solid #eee;background-color:#ffffff;margin:0;padding:0;display:inline-block;}
</style><script>
x = 0;
window.onload = function(){
for(i=0;i<3200;i++){
var newBlock = document.createElement('div');
newBlock.setAttribute('class', 'blocks');
newBlock.setAttribute('id','blockId'+x);
newBlock.setAttribute('onclick','change(this);');
document.getElementById('theBlock').appendChild(newBlock);
x++;
}
}
function change(x){
x.style.backgroundColor = '#000000';
}
</script></head><body><div id="theBlock"></div></body></html>
然而,由于内联 Javascript 不是最干净的编码方式,所以我尝试使用 this 引用来代替 change() 来创建一个函数,如下所示:
document.getElementsByClassName('blocks').onclick = function(){
this.style.backgroundColor = "#000000";
}
但是这个函数似乎并没有真正做任何事情。我不确定这是因为它没有正确引用对象,还是格式不正确,但我的控制台似乎没有发现任何问题,它就是不起作用。
希望这比我第一次尝试回答这个问题更有意义。
最佳答案
编辑:根据评论中的建议更改了事件监听器代码。
document.getElementsByClassName('blocks')
是一个 array NodeList,其中包含类为 blocks
的所有元素。所以你不能为所有这些添加一个均匀的监听器。
试试这个:
var arr = document.getElementsByClassName('blocks');
var len = arr.length;
var toBlack = function() {this.style.backgroundColor = '#000000';}
for (var i=0; i<len; i++) {
arr[i].onclick = toBlack;
}
这遍历 array NodeList 并为每个元素附加一个事件监听器。
关于Javascript 此引用可内联使用,但并非没有内联引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25614853/