如何在JavaScript中增加变量的范围?

时间:2011-09-21 14:50:47

标签: javascript jquery

我有以下代码:

$('.task-list').each(function(list, response) {
    response = $('#' + this.id).sortable('toArray');
});
console.log(response);

我得到的错误是未定义的响应。我尝试将第2行调整为var response但得到了相同的错误。

我正在尝试通过循环遍历页面上的项目来构建数据数组,然后向服务器提交单个ajax响应以进行更新。

4 个答案:

答案 0 :(得分:5)

您可能需要$.map代替:

var response = $('.task-list').map(function() {
    return $(this).sortable('toArray');
});

console.log(response)

答案 1 :(得分:3)

目前还不是很清楚你要完成什么,因为你在每次迭代中都会覆盖响应的价值。这可能更接近您的期望:

var response = [];
$('.task-list').each(function() {
    response.push($(this).sortable('toArray'));
});
// response will now be an array, where each item is another array from each .task-list
console.log(response);

答案 2 :(得分:1)

不确定我是否拥有each委托的正确参数,但这是如何将范围扩展到外面:

var response;
$('.task-list').each(function(list) {
    response = $('#' + this.id).sortable('toArray');
});
console.log(response);

答案 3 :(得分:-1)

在函数外移动(或更确切地说,声明)变量:

var response;
$('.task-list').each(function(list, response) {
    response = $('#' + this.id).sortable('toArray');
});
console.log(response);

第二个例子更接近我的想法,但我不清楚你想收集什么数据。

var response = [];
$('.task-list').each(function() {
    response.push($('#' + this.id). <<some data from this element??>>
});
console.log(response);