2012-03-02 16 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);、関数の宣言で、私は思うparamとしてデータを追加します。あなたがコールバックとしての機能parseJSONコールに渡している。このライン

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

1

あなたがそうのように、機能自体を渡したいほとんどの場合:あなたが今持っているコードで

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

は、parseJSON()が最初に呼び出され、その結果は、コールバックとして渡されます。

また、あなたはコールバック関数のシグネチャはjQueryの期待するものに準拠していることを確認する必要があります - 参照:http://api.jquery.com/jQuery.getJSON/ だからあなたparseJSON機能では、あなたはおそらくそうのように、引数としてdataを追加する必要があります。

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

(関数呼び出しをコールバックとして使用することは必ずしも間違いである必要はないことに注意してください)実際のコールバック関数を戻り値として渡す場合は、呼び出しを行うことができます。 :

function getParseCallBack() { 
    return parseJSON; 
} 

次にあなたができる:

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

私はあなたがこの時点でこれを使用することを示唆していないよ - 私はちょうど機能と関数の呼び出しとの違いを明確にしようとしている)

+0

ありがとうございました!今それは完全に動作します:) – marziobs

関連する問題