我正在使用jQuery和我使用Slim构建的API创建移动应用程序。基于数组的动态侦听器
我的总体目标是创建一个按钮列表,当单击它时将调用具有适当参数的函数。
我成功将我的请求发送到slim,获取用户列表并将结果存储在全局User对象数组中。
接下来,我通过数组附加html到文档来显示按钮。同时,我添加了一个点击监听器。听众得到补充,但不像我期望的那样。
用户是具有全局作用域的用户对象数组。用户对象可以归为[{“name”:“用户名”}]。
也可能是我在回电时这样做的事实。
$.getJSON(url, function(data){
for(i=0;i<data.length;i++)
{
var u = new User();
u.name = data[i]['name'];
}
})
//The success handler DOES get called.
.success(function() {
for(var i=0; i<users.length; i++)
{
//this part works. users[i] is accessed as expected.
var html_string = '<li>'+users[i].name+'</li>';
$("#myUL").append(html_string);
$("#myUL li:last").click(function(){
//logs undefined
console.log(users[i].name);
//Handle the event
eventHandleFunction()
});
}
})
我不够好,精通一般要知道我在做什么不属于最佳实践编程,但我在JavaScript这样文盲,我不知道解决的正确方法它。除了回答问题之外,我真的很感谢任何花时间指点我有用资源的人。
更新:阅读关于使用委托来分配处理程序的答案后,我已经更新了一下我的代码。现在看起来像这样。注意:我只是没有更新上面的代码才能得到原始问题的“为什么”部分的答案。
$("#myUL").delegate("li","click",function(){
//sets the attribute name of the global var user
user.name = $(this).text();
//lets see what user.name is now. Oh, look. It's what i expect
alert(user.name);
//do whatever else i want to do here.
});
//This json request is now (i believe) entirely unnecessary to answer the question.
$.getJSON(url, function(data){
for(i=0;i<data.length;i++)
{
var u = new User();
u.name = data[i]['name'];
}
})
//The success handler DOES get called.
.success(function() {
//No longer relevant
})
这引起了我重写一段代码,但一旦我做了(和RTFM上代表)我得到了它的工作。我的问题的'为什么'部分的任何输入? – Jake 2012-03-10 13:47:58
@Jake我更新了答案阅读更新部分中的评论 – Rafay 2012-03-10 13:55:58