在循环中绑定点击事件处理程序,导致jQuery中的问题

编程入门 行业动态 更新时间:2024-10-14 00:32:21
本文介绍了在循环中绑定点击事件处理程序,导致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中的问题

本文发布于:2023-11-27 22:02:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639765.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   事件   程序   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!