0

I've been working on a project involving generating and changing a <div>. Anyways, it would be a pain to have to do <div id="drawn" onclick="changeColor(this)"></div> for 80 divs which I am working with.

I decided to use the addEventListener() function to enable an events to happen when clicked.

What I am trying to do is when a <div> is clicked, the color of it's background is changed.

When I try the code I am using, I get an Uncaught TypeError: Cannot set property 'backgroundColor' of undefined ' of null in the Javascript Console.

Here is my code:

function color(elment) {

elment.style.backgroundColor="orange"

}

document.getElementById("drawn").addEventListener("click", color(this), false)

What is causing the error in this code?

4

2 回答 2

0

这是因为您不会影响事件的函数处理程序,而是在执行它。试试这个:

document.getElementById("drawn").addEventListener("click", function() { color(this); }, false)

但是由于你有 80 个 div,从资源的角度来看,最好定义一个特定的函数来自动更改父 div 的颜色,而不需要参数:

function changeDivColor() {
    this.style.backgroundColor="orange"
}

接着:

document.getElementById("drawn").addEventListener("click", changeDivColor, false);

将导致 80 个 div 调用相同的处理程序,而以前的系统将实例化 80 个匿名处理程序做基本相同的事情。

编辑:有趣的是@elclanrs 和我刚刚在同一时间发布了相同的编辑:-)

于 2013-11-14T00:50:45.390 回答
0

你需要传递一个匿名函数,否则上下文this不是window元素:

document.getElementById("drawn").addEventListener("click", function(){
  color(this);
}, false);

你可以做的只是在你的color函数中使用上下文:

function color() {
  this.style.backgroundColor = "orange";
}

document.getElementById("drawn").addEventListener("click", color, false);
于 2013-11-14T00:49:20.170 回答