开发者

Change Attribute Every Second

I want an image to change e开发者_开发知识库very second. I'm having trouble with setInterval. Could someone post a quick snippet on how to do this

This is what I came up with.

var images = 'images/image_*.png';
for(var i = 1; i <= 5; i++){
    function changeImg(){
        var path = images.replace('*', i);
        $('img').attr('src', path);
    }
    setInterval('changeImg()', 1000);
}


In your code you are calling the setInterval function 5 times which really is not necessary. Also as the loop will execute once, the value of i will always be 5 so it won't work as you expect. You may try this instead:

var images = 'images/image_*.png';
var i = 1;
setInterval(function() {
    var path = images.replace('*', i);
    $('img').attr('src', path);
    i = i + 1;
    if (i == 6) i = 1;
}, 1000);


Your loop was still continuing without waiting. Try writing it this way:

var images = 'images/image_*.png',
    i      = 1;

function changeImg(){
    var path = images.replace('*', i);
    $('img').attr('src', path);
    i = (i == 5 ? 0 : i + 1);
}

window.setInterval(changeImg, 1000); 


var images = 'images/image_*.png';
var i = 1;
function changeImg(i){
    var path = images.replace('*', i);
    $('img').attr('src', path);
}

setInterval('changeImg('+ ( (i++)%6 ) +')', 1000);

Maybe something like this ? I didn't test it though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜