开发者

How do I increase the scope of a variable in JavaScript?

开发者 https://www.devze.com 2023-04-06 23:39 出处:网络
I\'ve got the following code: $(\'.task-list\').each(function(list, response) { response = $(\'#\' + this.id).sortable(\'toArray\');

I've got the following code:

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

The error I'm getting is re开发者_开发知识库sponse is undefined. I tried adjusting line 2 to be var response but got the same error.

I'm trying to build an array of data by looping over the items on the page and then submitting a single ajax response to the server to update it.


You probably want $.map instead:

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

console.log(response)


It's not very clear what you're trying to accomplish, as you're overriding the value of response during each iteration. This might be closer to what you're looking for:

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);


Not sure if I have the right parameters for the each delegate, but this is how to get the scope outside:

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


Move (or rather, declare) the variable outside the function:

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

This second example is closer to what I think you want, but I'm not clear what data you're trying to collect.

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

精彩评论

暂无评论...
验证码 换一张
取 消