我有一些照片,我希望他们每10秒钟整理一次页面。
如下:
,...
直到我们完成所有照片。
我的问题:
方法加载不起作用& 我不知道等待的方法
这是我的代码:
<html>
<head>
<title></title>
<script type="text/javascript" src='jq.js'></script>
</head>
<body>
<div></div>
<script type="text/javascript">
var images=["images/0.jpg",
"images/1.jpg",
"images/2.jpg",
"images/3.jpg",
"images/4.jpg",
"images/5.jpg",
"images/6.jpg",
"images/7.jpg",
"images/8.jpg",
"images/9.jpg",
"images/10.jpg"
];
for (var i=0;i<images.length;i++){
var imgtag = '<img src='+images[i]+' />';
$(imgtag).load(function() {
$('div').append(imgtag);
//Wait 10 sec ==> Is there a function to Waiting :-??
}
}
</script>
</body>
</html>
感谢您的回复。
答案 0 :(得分:1)
首先,您需要等待DOM ready事件,然后使用递归回调:
$(function() { // on DOM ready
var images = [
"images/0.jpg",
"images/1.jpg",
"images/2.jpg",
"images/3.jpg",
"images/4.jpg",
"images/5.jpg",
"images/6.jpg",
"images/7.jpg",
"images/8.jpg",
"images/9.jpg",
"images/10.jpg"
];
(function loadImg(index) {
if (index >= images.length) return; // no more image to load
$('#divId').append( $('<img />').attr('src', srcImg).load(function() {
// invoke this function again in 10 secs incrementing index by 1
setTimeout(function() { loadImg(index + 1); }, 10000);
}) );
})(0); // initiate loading sequence with first image index
});
答案 1 :(得分:0)
使用setInterval
功能。
var images=["images/0.jpg",
"images/1.jpg",
"images/2.jpg",
"images/3.jpg",
"images/4.jpg",
"images/5.jpg",
"images/6.jpg",
"images/7.jpg",
"images/8.jpg",
"images/9.jpg",
"images/10.jpg"
];
var count = 0;
function loadImage() {
if (count < images.length) {
var imgtag = '<img src='+images[count]+' />';
$('div').append(imgtag);
count++;
}
}
setInterval(loadImage, 10000);