2012-03-02 5 views
0

질문은 this과 관련되어 있지만 연결된 예제와 같은 익명의 함수를 사용하는 대신 명명 된 함수를 사용하여 나는 필요하다.jQuery로 명명 된 함수와 익명의 json 데이터 가져 오기

function parseJSON() 
{ 
    $('#dictionary').empty(); 
    $.each(data, function(entryIndex, entry) { /*error here*/ 
     var html = '<div class="entry">'; 
     html += '<h3 class="term">' + entry['term'] + '</h3>'; 
     html += '<div class="part">' + entry['part'] + '</div>'; 
     html += '<div class="definition">'; 
     html += entry['definition']; 
     if (entry['quote']) { 
      html += '<div class="quote">'; 
      $.each(entry['quote'], function(lineIndex, line) { 
      html += '<div class="quote-line">' + line + '</div>'; 
      }); 
      if (entry['author']) { 
       html += '<div class="quote-author">' + entry['author'] + '</div>'; 
       } 
     html += '</div>'; 
      } 
     html += '</div>'; 
     html += '</div>'; 
     $('#dictionary').append(html); 
     }); 
} 


$(document).ready(function() { 
$('#letter-b a').click(function() { 
$.getJSON('b.json', parseJSON()); 
return false; 
}); 
}); 

나는 점점 계속 이런 식으로 오류 "'데이터'을 정의되어 있지 않습니다." 어떤 사전에

[ 
     { 
     "term": "BACKBITE", 
     "part": "v.t.", 
     "definition": "To speak of a man as you find him when he can't find you." 
     }, 
     { 
     "term": "BEARD", 
     "part": "n.", 
     "definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the head." 
     }, 
     { 
     "term": "BEGGAR", 
     "part": "n.", 
     "definition": "One who has relied on the assistance of his friends." 
     }, 
     { 
     "term": "BELLADONNA", 
     "part": "n.", 
     "definition": "In Italian a beautiful lady; in English a deadly poison. A striking example of the essential identity of the two tongues." 
     } 
    ] 

감사 :

는 JSON 파일 (익명의 기능을 완벽하게 작동)입니다 ... 나는 내가 알고, 사소한 뭔가를 실종 해요,하지만 난 그것을 얻을 수 없다 암시.

+0

parseJSON 인수로 데이터를 전달 ... 함수 이름을 변경해보십시오 ... 이미 그 이름으로 빌드 된 함수가 있다고 생각합니다. – DG3

+0

jQuery에 parseJSON 함수가 있습니다. 함수의 이름을 다른 것으로 변경하면 어떻게 될까요? – dezso

답변

3

다음과 같아야합니다. $.getJSON('b.json', parseJSON);, 함수 선언에서 데이터를 매개 변수로 추가한다고 생각합니다. 당신은 콜백과 같은 기능 parseJSON전화에 전달하는이 라인

$.getJSON('b.json', parseJSON()); 

에서

1

.

당신과 같이, 함수 자체를 전달하고 싶었 대부분의 경우 : 당신이 지금 가지고있는 코드에서

$.getJSON('b.json', parseJSON); 

parseJSON()이 먼저 호출되고 그 결과는 콜백으로 전달됩니다.

또한, 확실 콜백 함수의 서명이 jQuery를 무엇을 기대하고 준수 확인해야합니다 - 참조 : parseJSON 기능에 따라서 http://api.jquery.com/jQuery.getJSON/ 을, 당신은 아마과 같이, 인자로 data을 추가해야합니다 :

function parseJSON(data) { 
    ...your code here... 
} 

(함수 호출을 콜백으로 사용하는 것은 항상 잘못된 것은 아닙니다. 실제로 함수가 실제 콜백 함수를 반환 값으로 전달하는 경우 호출 할 수 있습니다. 예를 들어 :

function getParseCallBack() { 
    return parseJSON; 
} 

그런 다음 당신은 할 수 :

$.getJSON('b.json', getParseCallBack()); 

나는이 시점에서이 사용을 제안하고 있지 않다 - 나는 단지 기능과 함수를 호출 사이의 차이를 명확히하기 위해 노력하고있어)

.
+0

모두 감사합니다! 이제 완벽하게 작동합니다 :) – marziobs

관련 문제