请大家帮忙看看:如何在事件处理函数中重定向"this"?
我定义了一个对象,它会自动生成两个DIV,并把它们插入到<body></body>中,但我希望这两个DIV在对象中是private的。我想给其中一个DIV添加一个CLICK事件,当它被CLICK时,会改变另一个DIV的背景色。由于这两个DIV在对象中是private的,所以我专门写了一个函数来做这件事。整个代码如下:
程序代码:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. xmlns="http://www. xml:lang="en" lang="en">
<head>
<title>Test Page</title>
<script type="text/javascript">
function MyClass(){
this._oDiv1 = document.createElement("div");
this._oDiv1.style.cssText = "width:200px; height:150px; background-color:#0c0";
document.body.appendChild(this._oDiv1);
this._oDiv2 = document.createElement("div");
this._oDiv2.style.cssText = "width:150px; height:30px; background-color:#f55; color:black; margin-top:10px; text-align: center";
this._oDiv2.innerHTML = "Change to blue";
document.body.appendChild(this._oDiv2);
}
MyClass.prototype.addClick = function(){
this._oDiv2.onclick = function(){
this._oDiv1.style.backgroundColor = "#00c"; //problem happens here
return false;
};
//alert(this._oDiv2.onclick.toString());
};
function start(){
var o = new MyClass();
o.addClick();
}
</script>
</head>
<body onload="start();">
</body>
</html>其中MyClass.prototype.addClick便是用来给this._oDiv2添加click事件的,但是这段代码不起作用,原因出在this._oDiv1.style.backgroundColor = "#00c";这一句:这里的this本应指向对象的当前实例,但在这里却指向了产生CLICK事件的那个元素(即_oDiv2),结果导致错误。我不知道该如何让这里的this正确的指向当前对象实例?请大家指点一下。先谢谢了。






),找到了一个解决办法,供大家参考。


),但我的思路是正确的。
。唉,啥时论坛里能实现普选呀?