我遇到了Javascript的奇怪問題。我得到的是一串特定的格式,我將嘗試創建一個表格。在Javascript中動態添加事件處理程序
該表將僅具有每行一個單元和所述字符串的格式是:
內容需要被顯示爲每個小區(行)
@將被傳遞到onmouseover
事件處理程序
參數,其當用戶將鼠標移動到顯示的文本上時被調用。
的JS代碼:
// the string of format
var stringProof = document.getElementById("stringProof").value;
var arrayOfProof = stringProof.split("#");
// find the table
var table = document.getElementById("proofTable");
// remove what's within
table.innerHTML = "";
for(var i = currentIndex*4;i < end;i++)
{
// iterative create the text, span, cell and row
var currentStepProof = arrayOfProof[i];
var elementsInCurrentStepProof = currentStepProof.split("@");
var tr = document.createElement("tr");
var td = document.createElement("td");
var span = document.createElement("span");
span.onmouseover = function() {alert(elementsInCurrentStepProof[1]);};
var text = document.createTextNode(elementsInCurrentStepProof[0]);
span.appendChild(text);
td.appendChild(span);
tr.appendChild(td);
table.appendChild(tr);
}
問題是,它並不重要行onmouseover
功能被觸發,只會提醒最後一行的參數,這意味着最後一排的onmouseover
函數覆蓋的參數傳遞給上一行的onmouseover
函數。
有什麼想法?非常感謝!! ~~
http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – georg