在循环中绑定点击事件处理程序,导致jQuery中的问题 [英] Binding click event handlers in a loop causing problems in jQuery

查看:157
本文介绍了在循环中绑定点击事件处理程序,导致jQuery中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行以下代码:

我将参数传递给一个函数,但它总是有最后一个对象运行的循环的值。我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆