【发布时间】:2010-10-04 19:07:10
【问题描述】:
基本上,我试图传递一个在 JSON 数组中定义的变量,该数组在 for 循环中解析,以便在 click 语句中访问。
$(document).ready(function() {
getJSON();
var usedID;
});
function readJSON() {
for (var i = 0; i < json.array.length; i ++) {
usedID = json.array[i].id;
var template = $('repeaterTemplate').clone();
template.removeAttr('id');
template.attr('id', 'k' + json.array.id);
var omega = json.array.id;
$('#repeater').append(template);
(function(o) {
$('#' + o).click(function() {
// this is where the submitID click function is now. It passes the omega value in
});
})(omega);
}
}
$('.submitID').click(function() {
submitNow(usedID);
}
现在我的 for 循环中有 submitID click 函数,它导致 submitNOW 函数被调用,但循环循环多次。谁能帮我将用户 ID 从 readJSON() 传递给 click 函数?
我的每个函数都出现解析错误:
var userID = [];
var j = 0;
$('.submitNOW').each(function() {
function(id) {
$(this).click(function() {
submitNow(id);
});
}(userID[j]);
});
【问题讨论】:
-
所以您希望每个
.submitID元素以不同的userID值调用submitNow?还是所有这些值都相同? -
您可能想研究使用 jQuery 的 'each' 方法来迭代数据,它会减少一些循环样板。
-
您在 for 循环中获得了
usedID值。因此,预计会有多个 ID。你想通过哪一个? -
-lincolnk,是的,我需要不同的用户 ID 值。对特定列表项进行点击操作时选择正确的值
-
@sandeepan 这是一种自调用方法——它被定义,然后以
omega作为参数立即调用。它用于保存循环内变量的值。
标签: javascript jquery scope