好吧,我不得不重新说出这个来更好地理解我所问的内容。Javascript this reference inline,but not without inline reference
所以我有一个块填充divs,我想让他们改变颜色,如果点击。所以,如果我使用这个的内联参考,该功能正常工作。
<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不是代码最干净的方式,所以我试图让使用这引用的函数,在地方变化(中)像这样:
document.getElementsByClassName('blocks').onclick = function(){
this.style.backgroundColor = "#000000";
}
但是这个功能似乎并没有真正做任何事情。我不确定这是否是它没有正确引用该对象的问题,或者是格式错误,但我的控制台似乎没有发现任何问题,它只是不起作用。
希望这比我在这个问题上的第一次尝试更有意义。
+1但是,最好在循环之前将事件处理程序存储在变量中;否则,每次迭代都会创建一个新的重复函数。准确地说,'getElementsByClassName'返回一个'NodeList'实例,它是类似数组的,但不是数组。 – Oriol 2014-09-02 02:07:47
@Oriol完成。另外,有关NodeList的区别很好。谢谢。 – flowstoneknight 2014-09-02 02:12:50