在循环中绑定单击事件处理程序会导致 jQuery 出现问题 [英] Binding click event handlers in a loop causing problems in jQuery
问题描述
我正在尝试运行以下代码:
I am trying to run the following code:
我将参数传递给函数,但它始终具有通过循环运行的最后一个对象的值.我在 stackoverflow 上阅读了一些关于它的文章,但我不知道如何让它在我的解决方案中运行.
I pass parameter to a function, but it always has the value of the last object run through the loop. I read some articles about it on stackoverflow, but I couldn't find out how to make it run in my solution.
对象是从服务器返回的 JSON 对象.它的所有值都是正确的.
The object is a JSON object returned from the server. All it's values are correct.
for(var i = 0;i<parents.length;i++){
var row = $(document.createElement("tr"));
var colName = $(document.createElement("td"));
var aDisplayCol = $(document.createElement("a"));
var parentId = parents[i]['PARENT_ID'];
aDisplayCol.attr("href","#").html(parents[i]['NAME']);
aDisplayCol.bind('click',function(){ alert(parentId);});
colName.append(aDisplayCol);
row.append(colName);
$('#pages tbody').append(row);
}
谢谢
推荐答案
这是范围问题.当事件处理函数被执行时,parentId
的值已经改变,不再是你所期望的.
It is a scope problem. By the time the event handler function is executed, the value of parentId
has changed and is not longer what you expected.
这可以解决,使原始事件处理函数由另一个函数返回,而另一个函数又将 parentId
的值作为参数传递:
This can be solved making the original event handler function be returned by another function which, in turn, is passed the value of parentId
as argument:
function getEventHandlerFunction(id){
return function() {
alert(id); // variable found in the closure with the expected value
};
}
aDisplayCol.bind('click', getEventHandlerFunction(parentId));
这篇关于在循环中绑定单击事件处理程序会导致 jQuery 出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!