简体   繁体   中英

Only display one array item at a time (Javascript)

I am trying to essentially create a ticker which shows a single string item taken from an array at a time. Basically I just want it to show a single item and then transition into the next, my Javascript skills are massively rudimentary (Jquery might be better for this.)

Here is my code:

var title= ['Orange', 'Apple', 'Mango', 'Airplane', 'Kiwi'];
for (var i=0; i<title.length; i++){
document.write(title[i]);
}

What do I have to add?

Thanks a bunch!

Start by learning about document.getElementById and setInterval .

http://jsfiddle.net/wtNhf/

HTML:

<span id="fruit"></span>

Javascript:

var title = ['Orange', 'Apple', 'Mango', 'Airplane', 'Kiwi'];

var i = 0;  // the index of the current item to show

setInterval(function() {            // setInterval makes it run repeatedly
    document
        .getElementById('fruit')
        .innerHTML = title[i++];    // get the item and increment i to move to the next
    if (i == title.length) i = 0;   // reset to first element if you've reached the end
}, 1000);                           // 1000 milliseconds == 1 second

http://jsfiddle.net/3fj9E/1/

js

 var span = $('span');
 var div = 0;
 var fading_in = function () {
 $(span[div++] || []).fadeIn(500, arguments.callee);
 }
setTimeout(fading_in, 400);

html

 <div id='example'>
 <span>orange </span>
 <span>apple </span>
 <span>kiwi </span>
<span>banana </span>
<span> melon</span>
</div>

css

 span {display:none}

I tried to keep it at its simplest

HTML

<div id="my_id"></div>

Javascript

var counter = 0;
var words = ['jaja', 'jojo', 'lol', 'troll', 'pk!'];
var my_div = document.getElementById('my_id');

function next_word()
{
    my_div.innerHTML = words[counter % words.length];
    counter += 1;
}

setInterval(next_word, 100);

http://jsfiddle.net/zTLqe/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM