1

我试图在用户单击HTML表格中的单元格时注册一个匿名函数。下面是一些原始的,纯粹的代码:Firefox Javascript事件匿名函数

document.getElementById(
    "course"+displayed_year_index+occurrences_indices[displayed_year_index]).onclick = 
     eval("function() {PrintReceipt("+result.years[result_year_index].rul_code+");};"); 

注意使用eval,因为这坐落在一个循环,匿名函数是每次都不同轮。

可以这么说,这在Firefox 2中绝对正常。但是,Firefox 3会抛出一个'语法错误',在单词'function'之后指向括号内。

有没有人有什么聪明的想法,我该如何解决这个问题?


只是为了让晶莹剔透什么,我试图做的,这里有一个更加简化的例子:

for (index=0; index<4; index++) { 
    document.getElementById("div"+index).onclick = 
     eval("function() {Foo(index);};"); 
} 

换句话说,我希望与不同的参数值来触发同样的功能每个div

+0

请张贴循环。 – Tom 2008-11-17 14:24:07

回答

4

恕我直言关闭不应该在这种情况下使用,也没有必要建立一个新的功能,为每个点击数(使用更多的内存比必要) eval是错误的答案。

您知道getElementById获得的元素是一个对象,您可以为其指定值?

for (/* your definition */) { 
    var e = document.getElementById(
    "course"+displayed_year_index+occurrences_indices[displayed_year_index] 
); 
    e.rul_code = result.years[result_year_index].rul_code; 
    e.onclick = PrintReceipt; 
} 

但是,你应该首先定义PrintReceipt:

function PrintReceipt() { 
    //This function is called as an onclick handler, and "this" is a reference to the element that was clicked. 
    if (this.rul_code === undefined) { return; } 
    //Do what you want with this.rul_code 
    alert (this.rul_code); 
} 
5

你有没有尝试过这样的事情?

document.getElementById('course' + displayed_year_index + occurences_indices[displayed_year_index]) = 
    function (nr) 
    { 
     return function() { PrintReceipt(nr) } 
    } (result.years[result_year_index].rul_code); 

请问您可以发布循环以帮助我们找到问题,而不是让我们猜测您正在尝试做什么?

+1

好的答案,但是一个很好的解释关闭的链接会有很大的帮助。我理解你的代码,但它仍然让我感到害怕;)不知道封闭是什么的人不会有机会。不幸的是,我还没有看到任何关于闭包在任何地方的清晰,简洁的解释:( – Gareth 2008-11-17 14:49:17

+0

不幸的是,我需要分配给onclick事件,并且因此无法将参数传递给匿名函数 – 2008-11-17 16:02:22

0

好像这是你想要去的方向:

document.getElementById("course"+displayed_year_index+occurrences_indices[displayed_year_index]).addeventlistener("click", function() { 
    var current_rul_code = result.years[result_year_index].rul_code; 
    PrintReceipt(current_rul_code); 
}, true); 

这应当引起每到onclick事件是一个不同的作用域(每次循环)中创建的。 Closures将照顾其余。

+0

This does not'因为在onclick调用PrintReceipt的参数需要是一个常量。 – 2008-11-17 16:03:36

+0

它不应该是一个常量,因为当事件触发时,函数将在其原始范围内调用。 – 2008-11-17 16:41:40

1

像Tom建议的那样使用闭包。

继承人约翰Resig的一个很好的解释:How Closures Work(PDF)