2014-09-02 78 views
0

好吧,我不得不重新说出这个来更好地理解我所问的内容。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"; 
} 

但是这个功能似乎并没有真正做任何事情。我不确定这是否是它没有正确引用该对象的问题,或者是格式错误,但我的控制台似乎没有发现任何问题,它只是不起作用。

希望这比我在这个问题上的第一次尝试更有意义。

回答

3

编辑:更改事件监听器代码,根据建议在评论中。

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; 
} 

此遍历阵列节点列表并附加一个事件监听到的每个元素。

+2

+1但是,最好在循环之前将事件处理程序存储在变量中;否则,每次迭代都会创建一个新的重复函数。准确地说,'getElementsByClassName'返回一个'NodeList'实例,它是类似数组的,但不是数组。 – Oriol 2014-09-02 02:07:47

+0

@Oriol完成。另外,有关NodeList的区别很好。谢谢。 – flowstoneknight 2014-09-02 02:12:50

1
//newBlock.setAttribute('onclick','change(this);'); 
     newBlock.onclick = change; 
... .... 
function change() { 
    this.style.backgroundColor = '#000000'; 
} 

但是当我测试你的代码时,它在我的电脑上工作在IE9上。

+0

我喜欢这里的想法,但它在Chrome上抛出错误。我认为它引用了函数范围之外的局部变量。 – 2014-09-02 02:27:20

+0

@ ThomasCheney-它也应该在Chrome中正常工作。不要使用* setAttribute *版本,坚持分配属性。 – RobG 2014-09-02 02:44:25

+0

我认为它在我的Chrome上不起作用,因为变量名newBlock只是一个临时名称,但我可能犯了一个错误,因为它阻止了所有块渲染到页面。 – 2014-09-02 03:09:57