2011-09-21 38 views
0

我有下面的代码:如何增加JavaScript中变量的范围?

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

我得到的错误是反应是不确定的。我尝试调整第2行为var response,但得到了相同的错误。

我试图通过循环页面上的项目,然后提交一个单一的Ajax响应更新它的服务器来构建一个数据数组。

+0

什么'.sortable( '指定者')'做什么? –

+0

你能澄清你想要的结果吗?有多少个.task-list元素? – jmar777

+2

'$(this)'而不是'$('#'+ this.id)'请...... –

回答

5

你可能想$.map代替:

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

console.log(response) 
-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); 
+5

请注意,'response'是他的'each'迭代器中的一个参数名称。 – jmar777

+0

这可能是我的代码中的一个错误 - 我在这里没有经历过。在这个答案中建议的代码不起作用,虽然这次没有错误,但当控制台日志行中包含某些内容时,响应是空的。 – cjm2671

+0

是真的......但那不是他问的问题。这看起来似乎是他想要做什么的错误方式。 –

1

不知道如果我对each代表正确的参数,但是这是如何获得外部的范围:

var response; 
$('.task-list').each(function(list) { 
    response = $('#' + this.id).sortable('toArray'); 
}); 
console.log(response); 
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); 
+0

这是正确的答案 - 你是正确的 - 有多个错误,响应不应该是一个参数。 – cjm2671

+0

很酷。也请看@ IAbstractDownvoteFactor的答案。它会给你和我一样的'响应'值,但是有点清洁(IMO)。 – jmar777