日期:2014-05-16  浏览次数:20396 次

this的问题,急求解决
代码:
<head>
        .......
<script   type= "text/javascript "   src= "/script/prototype.js "> </script>   //引入prototype类库
<script   type= "text/javascript "   src= "/script/register.js "> </script> //引入自己定义类
</head>
<body   onload= "Register.init() ">
....
<input   type= "text "   value= " "   id= "email "   class= " "   />
<input   type= "text "   value= " "   id= "pass "   class= " "   />
<input   type= "text "   value= " "   id= "add "   class= " "   />

.....

register.js
var   Register   =   function(){
function   Showspen(){
alert(this.id);//这里有问题!!
Element.addClassName(this.id   +   '_span ', 'red ');
}
return   {
init:   function   setEvent(){
var   inputlist   =   $( 'email ', 'pass ', 'add '),i;
for   (i=0;   i <inputlist.length;   i++)   {
Event.observe(inputlist[i],   'focus ',   Showspen);

}
}
}
}();

问题出在Showspen中,alert(this.id)
Firefox种执行,可以顺利得到值,但是IE执行通不过
测试IE中的this值,似乎是windows对象了
请教应该怎么修改,让两个浏览器都可以得到this对象?

------解决方案--------------------
楼上的都在说什么啊
this指针和document.getElementById(this); ,event.srcElement都没关系

注意this指针的指向对象

var Register = function(){
this.Test = "Register ";
var PrivateID = this.id;
function Showspen(){
this.Test = "Showspen ";
alert(PrivateID);//这里有问题!!
alert( '当前指针指向: '+ this.Test);
Element.addClassName(PrivateID + '_span ', 'red ');
}
return {
init: function setEvent(){
var inputlist = $( 'email ', 'pass ', 'add '),i;
for (i=0; i <inputlist.length; i++) {
Event.observe(inputlist[i], 'focus ', Showspen);
}
}
}
}();

注意js中function()自身可以声明类,所以Showspen的this指针实际上只向了Showspen自己
所以可以定义一个私有变量替代