簡體   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