导读:
o.attachEvent("onclick", function(){ doClick(i); });
document.body.appendChild(o);
}
alert出来都是10,要达到的目的很简单,一眼看出,但结果不如所想。如何解决?
---------------------------------------------------------------
I dont't know the reason exactly, but I can tell you that 'i' seems to be a Global variable even if you put the codes in a function.
use my code:
<script>
Function.prototype.getHandler = function (obj) {
var oThis = this;
var argu = Array.prototype.slice.call(arguments, 1);
return function (){
oThis.apply(obj, argu);
};
};
function doClick(x) {
alert(x);
};
for (var i=0;i<10;i++) {
var o = document.createElement("input");
o.attachEvent("onclick", doClick.getHandler(null,i));
document.body.appendChild(o);
}
If you don't know about "call","apply", you can see the Javascript Reference, or
http://community.csdn.net/Expert/topic/3191/3191873.xml?temp=.337063
Good luck.
---------------------------------------------------------------
是这样的,attachEvent虽然把执行定义好了,但是,并没有执行。
而当真正click的时候,这时i的值已经是10了,所以,会alert出来10。
function(){}相当于Function()函数,以下这么写估计就会很清楚了。
o.attachEvent("onclick", function(){ doClick(i); });
document.body.appendChild(o);
}
alert出来都是10,要达到的目的很简单,一眼看出,但结果不如所想。如何解决?
---------------------------------------------------------------
I dont't know the reason exactly, but I can tell you that 'i' seems to be a Global variable even if you put the codes in a function.
use my code:
<script>
Function.prototype.getHandler = function (obj) {
var oThis = this;
var argu = Array.prototype.slice.call(arguments, 1);
return function (){
oThis.apply(obj, argu);
};
};
function doClick(x) {
alert(x);
};
for (var i=0;i<10;i++) {
var o = document.createElement("input");
o.attachEvent("onclick", doClick.getHandler(null,i));
document.body.appendChild(o);
}
If you don't know about "call","apply", you can see the Javascript Reference, or
http://community.csdn.net/Expert/topic/3191/3191873.xml?temp=.337063
Good luck.
---------------------------------------------------------------
是这样的,attachEvent虽然把执行定义好了,但是,并没有执行。
而当真正click的时候,这时i的值已经是10了,所以,会alert出来10。
function(){}相当于Function()函数,以下这么写估计就会很清楚了。