2013-09-28 17 views
5

Próbuję dodać tekst do elementu div przy użyciu JavaScript i/lub jQuery, a następnie zmieniać tekst na inny tekst co 10 sekund - tak, jak w przypadku pokazu slajdów tylko zwykłego tekstu. Oto mój kod:Javascript Text Slideshow

<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

Pierwszy arg na 'setTimeout' jest funkcją. 'setTimeout' po prostu wywołuje tę funkcję rekurencyjnie. Więc w twoim przypadku wystarczy umieścić kod js w funkcji, a następnie wpisz nazwę tej funkcji jako pierwszy argument. – stackptr

Odpowiedz

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

Oto propozycja z zwykły JS

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

Demo here

Jeśli chcesz użyć jQuery można użyć to: $('#textslide p:first').text(quotes[counter]);

Demo here

0

Zamiast chwilę, zastosowanie:

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

To nie _setIntervale_, a raczej _setInterval_. –

0

Użyj funkcji i wywołać ją na onload ciała

<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>