繁体   English   中英

Firefox Javascript事件匿名功能

[英]Firefox Javascript Events Anonymous Function

当用户单击HTML表中的单元格时,我试图注册一个匿名函数。 这是一些原始的,纯净的代码:

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抛出“语法错误”,指向“功能”一词后的括号内。

有人对我该如何解决有任何聪明的主意吗?


只是为了让我清楚地知道我要做什么,这是一个大大简化的示例:

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

换句话说,我希望为每个div使用不同的参数值来触发相同的函数。

你尝试过这样的事情吗?

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

您能否发布循环信息以帮助我们发现问题,而不是让我们猜测您要做什么?

在这种情况下,不应使用IMHO闭包,也无需为每个onlick创建新函数(使用的内存多于必要),并且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);
}

使用汤姆建议的闭包。

这是John Resig的一个很好的解释: 封闭的工作原理 (pdf)

看来这是您要走的方向:

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事件在不同的范围内创建(循环的每次迭代)。 封闭处将负责其余的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM