2013-09-28 273 views
5

Tôi đang cố gắng thêm văn bản vào một div bằng JavaScript và/hoặc jQuery và sau đó thay đổi văn bản đó thành văn bản khác nhau sau mỗi 10 giây - vì vậy phần nào giống như trình chiếu chỉ văn bản thuần túy. Dưới đây là mã của tôi:Trình chiếu văn bản Javascript

<div id="textslide"><p></p></div> 

<script> 

var quotes = new Array(); 

quotes[0] = "quote1"; 
quotes[1] = "quote2"; 
quotes[2] = "quote3"; 
quotes[3] = "quote4"; 
quotes[4] = "quote5"; 

var counter = 0; 

while (true) { 
    if (counter > 4) counter = 0; 
    document.getElementById('textslide').firstChild.innerHTML = quotes[counter]; 
    counter++; 
    setTimeout(// not sure what to put here, 500); // Want to delay loop iteration 
} 

</script> 
+0

Giá trị arg đầu tiên cho 'setTimeout' là hàm. 'setTimeout' đơn giản gọi hàm đó đệ quy. Vì vậy, trong trường hợp của bạn, chỉ cần đặt mã js trong một hàm, và sau đó viết tên của hàm đó làm arg đầu tiên. – stackptr

Trả lời

7

HTML:

<div id="textslide"><p></p></div> 

JavaScript/jQuery:

var quotes = [ 
    "quote1", 
    "quote2", 
    "quote3", 
    "quote4", 
    "quote5", 
    ]; 

var i = 0; 

setInterval(function() { 
$("#textslide").html(quotes[i]); 
    if (i == quotes.length) { 
     i = 0; 
    } 
    else { 
     i++; 
    } 
}, 10 * 1000); 

Working demo here

1

Dưới đây là một gợi ý với đồng bằng JS

function loop() { 
    if (counter > 4) counter = 0; 
    document.getElementById('textslide').firstElementChild.innerHTML = quotes[counter]; 
    counter++; 
    setTimeout(loop, 500); 
} 
loop(); 

Demo here

Nếu bạn muốn sử dụng jQuery bạn có thể sử dụng này: $('#textslide p:first').text(quotes[counter]);

Demo here

0

Thay vì thời gian, sử dụng:

setInterval(function() { 
    //do your work here 
}, 10000); 
+2

Nó không phải là _setIntervale_, thay vì _setInterval_. –

0

Sử dụng hàm và gọi hàm này trên tải trọng cơ thể

<html> 
    <head> 
     <script> 
     var counter = 0; 

     function changeText() 
     { 
     var quotes = new Array(); 

     quotes[0] = "quote1"; 
     quotes[1] = "quote2"; 
     quotes[2] = "quote3"; 
     quotes[3] = "quote4"; 
     quotes[4] = "quote5"; 

     if (counter > 4) 
      { 
      counter = 0; 
      } 

     document.getElementById("textslide").innerHTML = quotes[counter]; 

     setTimeout(function(){changeText()},10000); 
     counter ++; 
     } 
     </script> 
    </head> 
    <body onload="changeText();"> 
     <p id="textslide"></p> 
    </body> 
</html>