我试图从Pokemon API中获取名称并将其放入html中的div字段,但jQuery中的.text()函数似乎并没有将文本放入html中把它放在.getJSON函数中。只是好奇这个问题会是什么?感谢。
<div class="container">
<div class="row">
<div class="col-sm-3" id="1">
<div id="name1"></div>
</div>
<div class="col-sm-3" id="2">
<div id="name2"></div>
</div>
<div class="col-sm-3" id="3">
<div id="name3"></div>
</div>
<div class="col-sm-3" id="4">
<div id="name4"></div>
</div>
</div>
</div>
Javascript代码
$(document).ready(function() {
/*Works*/
for(var j = 1; j < 5; j++){
$("#name" + j).text("HELLO");
}
/*Doesn't work*/
for(var j = 1; j < 5; j++){
var webAddress2 = "http://pokeapi.co/api/v1/pokemon/" + j;
$.getJSON(webAddress2, function(data) {
console.log("test");
$("#name" + j).text("SOME TEXT");
});
}
});
答案 0 :(得分:1)
由于getJSON
在成功时是异步的,因此执行j
的值将是5
。没有标识为name5
的元素,因此不会发生任何事情。要使其有效,请使用 closure 功能。
$(document).ready(function() {
/*Works*/
for (var j = 1; j < 5; j++) {
$("#name" + j).text("HELLO");
}
/*Doesn't work*/
for (var j = 1; j < 5; j++) {
var webAddress2 = "http://pokeapi.co/api/v1/pokemon/" + j;
(function(j) {
$.getJSON(webAddress2, function(data) {
console.log("test");
$("#name" + j).text("SOME TEXT");
});
})(j);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3" id="1">
<div id="name1"></div>
</div>
<div class="col-sm-3" id="2">
<div id="name2"></div>
</div>
<div class="col-sm-3" id="3">
<div id="name3"></div>
</div>
<div class="col-sm-3" id="4">
<div id="name4"></div>
</div>
</div>
</div>
或使用 let
作为块级范围变量。
$(document).ready(function() {
/*Works*/
for (var j = 1; j < 5; j++) {
$("#name" + j).text("HELLO");
}
/*Doesn't work*/
for (let j = 1; j < 5; j++) {
var webAddress2 = "http://pokeapi.co/api/v1/pokemon/" + j;
$.getJSON(webAddress2, function(data) {
console.log("test");
$("#name" + j).text("SOME TEXT");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3" id="1">
<div id="name1"></div>
</div>
<div class="col-sm-3" id="2">
<div id="name2"></div>
</div>
<div class="col-sm-3" id="3">
<div id="name3"></div>
</div>
<div class="col-sm-3" id="4">
<div id="name4"></div>
</div>
</div>
</div>