![]() |
#2
netwind0072010-12-14 05:52
|

<!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正确的指向当前对象实例?请大家指点一下。先谢谢了。<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>