尝试编写一个打印出我的播放列表的循环语句,但我的浏览器只是无限循环

时间:2015-09-15 00:46:11

标签: javascript html loops infinite-loop

所以,我要写一个循环语句打印出我的播放列表,但我的浏览器只是无限循环而不是加载文本和内容。我怎样才能调整我的代码呢?

<!DOCTYPE html>
    <html>
    <head>
        <title>9. Looping Statements in Javascript</title>
    </head>
    <body>
        <h1>9. Looping Statements in Javascript</h1>
        <div id="container"></div>
        <div id="playlist"></div>
        <script>
            var playlist = [];
            playlist[0] = "Willy Wesly";
            playlist[1] = "Childish Gambino";
            playlist[2] = "Chance The Rapper";
            playlist[3] = "Travi$ Scott";
            playlist[4] = "Yeezy";

            // while
            var i = 0;
            while (i < playlist.length); {
                var element = document.getElementById('playlist').innerHTML = playlist;
                element.innerHTML = 'Now Playing: ' + playlist[i], i++;
                container.appendChild(element);
            }
        </script>
    </body>
    </html>

2 个答案:

答案 0 :(得分:4)

尝试此操作在关闭括号后删除分号:

var i = 0;
while (i < playlist.length) {
    var element = document.getElementById('playlist').innerHTML = playlist;
    element.innerHTML = 'Now Playing: ' + playlist[i], i++;
    container.appendChild(element);
}

答案 1 :(得分:0)

你不需要追加元素,它已经是dom的一部分了。只需添加到innerHTML,(这就是我觉得它看起来最漂亮的方式)

var i = 0;
var element = document.getElementById('playlist');
element.innerHTML = 'Now Playing:<br/>';

while (i++ < playlist.length) {
    element.innerHTML += playlist[i] + '<br/>';
}