求助一个关于 this 的问题
正在做了一个包装DIV层的控件。但是在层的onclick 中 不知道如何找到控件的实例
控件大概如
<html>
<head> <title> 测试 </title> </head>
<body>
<div id= "Div1 " style= "width: 100%; height:10px; background-color: #ff0000 "> </div>
<br/>
<br/>
<div id= "Div2 " style= "width: 100%; height:10px; background-color: #00ff00 "> </div>
<script type= "text/javascript ">
function DivControl(divname)
{
this.a = " ";
this.b = " ";
this.mydiv = document.getElementById(divname);
this.mydiv.onclick = function()
{
alert(this.a); //请问如何在这里访问this,这里的this 是mydiv
}
}
var div1= new DivControl( "Div1 ");
div1.a = "a1 ";
div1.b = "b1 ";
var div2= new DivControl( "Div2 ");
div2.a = "a2 ";
div2.b = "b2 ";
</script>
</body>
</html>
现在临时用一个全局哈希表保存控件的指针[ "DivName ", Control],但感觉语法不好,请问有什么好的实现方法?
------解决方案--------------------//方法一:
function DivControl(divname)
{
this.a = " ";
this.b = " ";
this.mydiv = document.getElementById(divname);
this.mydiv._Control = this;
this.mydiv.onclick = function()
{
alert(this._Control.a); //请问如何在这里访问this,这里的this 是mydiv
}
}
//方法二:
function DivControl(divname)
{
var me = this;
this.a = " ";
this.b = " ";
this.mydiv = document.getElementById(divname);
this.mydiv.onclick = function()
{
alert(me.a); //请问如何在这里访问this,这里的this 是mydiv
}
}