我想在#t1,#t2和#t3中放置有关视频的信息,但所有内容都放在#t3中。代码中的错误在哪里?
$(function(){
for (var i = 1; i < 4; i++) {
var box = "#t" + i;
var id = "dQw4w9WgXcQ";
var img = "<img src='https://img.youtube.com/vi/" + id + "/default.jpg'>";
console.log(i);
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
$(box).prepend("viewCount: " + data.items[ 0 ].statistics.viewCount);
});
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
$(box).prepend("<h3>" + "Title" + data.items[0].snippet.title + "</h3>");
$(box).prepend("<h3>" + "Channel title" + data.items[0].snippet.channelTitle + "</h3>");
$(box).prepend(img);
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="t1"></div>
<div id="t2"></div>
<div id="t3"></div>
答案 0 :(得分:3)
Closures...
将所有内容都包装在一个闭包中,这将为每次迭代创建一个新的scope
。
$(function(){
for (var i = 1; i < 4; i++) {
(function(i)
var box = "#t" + i;
var id = "dQw4w9WgXcQ";
var img = "<img src='https://img.youtube.com/vi/" + id + "/default.jpg'>";
console.log(i);
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
$(box).prepend("viewCount: " + data.items[ 0 ].statistics.viewCount);
});
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
$(box).prepend("<h3>" + "Title" + data.items[0].snippet.title + "</h3>");
$(box).prepend("<h3>" + "Channel title" + data.items[0].snippet.channelTitle + "</h3>");
$(box).prepend(img);
});
}
})(i);
});
答案 1 :(得分:1)
$.getJSON
是异步的,处理程序将在收到响应时被调用。但是for-loop
不会等待处理程序被调用!
创建inner-function
并将i
的值作为参数传递,因为i
的值inner-function
将保持不变。
$(function() {
for (var i = 1; i < 4; i++) {
var tobeCalled = function(i) {
var box = "#t" + i;
var id = "dQw4w9WgXcQ";
var img = "<img src='https://img.youtube.com/vi/" + id + "/default.jpg'>";
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
$(box).prepend("viewCount: " + data.items[0].statistics.viewCount);
});
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
$(box).prepend("<h3>" + "Title" + data.items[0].snippet.title + "</h3>");
$(box).prepend("<h3>" + "Channel title" + data.items[0].snippet.channelTitle + "</h3>");
$(box).prepend(img);
});
}
tobeCalled(i);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="t1">
<h2>1</h2>
</div>
<div id="t2">
<h2>2</h2>
</div>
<div id="t3">
<h2>3</h2>
</div>