2010-03-16 27 views
3

我不确定如何描述我想要的内容。我想定义一个函数,其参数是一个本地VALUE而不是一个参考。创建具有值参数的函数引用not references

说,我有我想创建

for(i = 0; i < 10; i++){ 
    var div = document.createElement("div"); 
    div.onclick = function(){alert(i);}; 
    document.appendChild(div); 
} 

现在我相信在这个例子中,无论我点击了什么格,它会提醒“10”的对象列表;因为这是变量i的最后一个值;

有没有办法/我如何创建一个函数,参数是我在指定函数时的值...如果这是有道理的。

+1

在函数内部,'i'是一个捕获的变量,而不是一个参数。 – SLaks 2010-03-16 00:11:18

+0

参见: http://stackoverflow.com/questions/1734749/ http://stackoverflow.com/questions/643542/ http://stackoverflow.com/questions/1582634/ HTTP:/ /stackoverflow.com/questions/1331769/ http://stackoverflow.com/questions/1552941/ http://stackoverflow.com/questions/750486/ http://stackoverflow.com/questions/933343/ http://stackoverflow.com/questions/1579978/ http://stackoverflow.com/questions/1413916/ ...以及更多... :) – CMS 2010-03-16 00:27:54

+0

@CMS:是的;我已经获得了很多回应这种问题的声誉。 – SLaks 2010-03-16 00:28:57

回答

5

您需要在另一个函数内部创建函数。

例如:

div.onclick = (function(innerI) { 
    return function() { alert(innerI); } 
})(i); 

此代码创建一个函数,它的参数和返回使用参数的函数。由于外部函数的参数是按值传递的,它可以解决你的问题。

它通常是更清晰,使外层功能的单独的命名功能,就像这样:

function buildClickHandler(i) { 
    return function() { alert(i); }; 
} 

for(i = 0; i < 10; i++){ 
    var div = document.createElement("div"); 
    div.onclick = buildClickHandler(i); 
    document.appendChild(div); 
} 
+1

+1超高速度和正确性! – Anurag 2010-03-16 00:13:52

+0

现在我想如果我想通过“这个”,我还得克制功能吗? div.onclick = function(){somefunction(i,this)}; – 2010-03-16 00:24:56

+0

@Sheldon:正确。或者,'someFunc.call(this,i)'将允许你在'someFunc'中使用'this'。 – SLaks 2010-03-16 00:27:33

0

你可以使用匿名函数:

for(i = 0; i < 10; i++){ 
    (function(i){ 
     var div = document.createElement("div"); 
     div.onclick = function(){alert(i);}; 
     document.appendChild(div); 
    })(i) 
} 
相关问题