开发者

jQuery update element using .each() [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

HTML code:

div id="updatePanel">​

jQuery code:

var data=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

$.each(data, function(index, value) {
  setTimeout(function(){ 
     $('#updatePanel').text(index);     
  },开发者_JAVA百科 5000 ); 
}); 

I want the updatePanel div content to be updated every 5 seconds. It should be 1 then wait 5 seconds, display 2, wait for another 5 seconds......

It doesn't work like what i expected. It waits for 5 seconds and display 9.

See the demo here: http://jsfiddle.net/vc7qB/4/


Change the }, 5000 ); to }, 5000*index );

This will make each item to wait 5 seconds more than the previous ...

Keep in mind that all the timeouts get created at the same time, but with different delay times..

It would be better to start with a single timeout and at each execution create the next one ..

like this

var data=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    function update(idx){
        setTimeout(function(){
        $('#updatePanel').text( data[idx] );
        if (idx < data.length - 1)
            update(idx+1);
        },1000);
    }

update(0);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜