2011-09-21 4 views
0

다음 코드가 있습니다.자바 스크립트에서 변수의 범위를 늘리려면 어떻게해야합니까?

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

응답이 잘못되었습니다. 응답은 정의되지 않았습니다. var response 수 2 줄 조정 시도했지만 동일한 오류가 있어요.

페이지의 항목을 반복 한 다음 서버에 단일 Ajax 응답을 제출하여 데이터 배열을 업데이트하려고합니다.

+0

'합니까? –

+0

결과를 원하는대로 명확히 할 수 있습니까? 얼마나 많은 .task-list 요소가 있습니까? – jmar777

+2

'$ ('#'+ this.id)'대신'$ (this)''... –

답변

5

:

`.sortable ('toArray') 무엇을
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'는 그의 각 반복자에있는 매개 변수 이름 중 하나라는 점에 유의하십시오. – 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); 
당신은 아마 대신 $.map을 원하는
+0

맞습니다. 올바른 답입니다. 여러 오류가 있었지만 응답이 매개 변수가되어서는 안되었습니다. – cjm2671

+0

차가움. 또한 @ IAbstractDownvoteFactor의 대답을 살펴보십시오. 그것은 내 것과 같은'response'에서 당신에게 동일한 가치를 줄 것이지만 조금 더 깨끗합니다 (IMO). – jmar777

관련 문제