$ .getJSON内外的映射

时间:2017-03-14 16:48:32

标签: jquery loops getjson

我遇到循环问题以及在jQuery中使用$ .getJSON()方法。我正在尝试映射finalWords数组,对于每个单词,我想进行API调用以获取每个单词的定义。

一旦我从API调用中获取数据,我想用另一个映射循环定义。但是,第二个参数“ind”将记录保持为“0”并且不会像我认为的那样增加。基本上这是一个问题因为我给每个人一个id“clue + ind”,我想用id改变css。

我对此很陌生,所以我不确定这是否是我在$ .getJSON或其他内容中的循环错误。有什么建议?谢谢!

var finalWords = ["smart", "jolly", "goofy", "clever", "graceful", "kind", "happy"]

finalWords.map(function(i, index){

  // loops thru finalWords array and then makes an API call to Wordnik
  $.getJSON(`http://api.wordnik.com:80/v4/word.json/${i}/definitions?limit=1&includeRelated=true&sourceDictionaries=all&useCanonical=true&includeTags=false&api_key=...`, function(data){

    data.map(function(j, ind){ 

   // loop thru data returned from API and give it a Bootstrap "col-md-8" class
      console.log(ind); //this logs 0 every time...
      $("#clues").append(`<div class="col-md-8" id="clue${ind+1}">${j.text}</div>`).css({"font-size":"1em"});
       $(`#clue${ind+1}`).css({"border":"1px solid black"}); //...so only the first div "#clue1" is given the border property
      $("#clues").append(`<div class="col-md-2" id="wordLength${ind+1}">${i.length} letters</div>`)
    });
  });

});

0 个答案:

没有答案