<div id="test"></div>
<script>
var str="1,2,3,4,5";
str = str.split(',');
for(var i = 0, len = str.length; i < len; i++){
(function(x){
setTimeout(function(){
document.getElementById('test').innerHTML += str[x]
},1000)
})(i)
}
</script>
这段代码 为什么没有每隔一秒这样显示
1
12
123
1234
12345而是直接 隔一秒后 直接 12345?期待

解决方案 »

  1.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <body>
    <div id="test"></div>
    <script>    
        var str="1,2,3,4,5",count = 0,inter = null;
        str = str.split(',');
        
    inter = setInterval(function(){
    if(str[count]){
    document.getElementById('test').innerHTML = str[count];
    count++;
    }else{
    clearInterval(inter)
    }
    },1000)
        
    </script></body>
    </html>
      

  2.   

    document.getElementById('test').innerHTML = str[count];把这句改成document.getElementById('test').innerHTML += str[count];就是你要的效果~·
      

  3.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <body>
    <div id="test"></div>
    <script>    
        var str="1,2,3,4,5";
        str = str.split(',');
        for(var i = 0, len = str.length; i < len; i++){
            (function(x){
                setTimeout(function(){
                    document.getElementById('test').innerHTML += str[x]
                },i * 1000)
            })(i)
        }
    </script>
    </body>
    </html>
      

  4.   


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <body>
    <div id="test"></div>
    <script>    
        var str="1,2,3,4,5";
        str = str.split(',');
        for(var i = 0, len = str.length; i < len; i++){
            (function(x){
                setTimeout(function(){
                    document.getElementById('test').innerHTML += str[x];
    alert(document.getElementById('test').innerHTML);//为了看的更清楚
                },i * 1000)
            })(i)
        }
    </script>
    </body>
    </html>