一次只显示一个数组项(Javascript)

时间:2013-03-28 20:55:45

标签: javascript arrays loops

我试图创建一个自动收录器,它显示一次从数组中取出的单个字符串项。基本上我只是想让它显示一个项目,然后过渡到下一个项目,我的Javascript技能非常简陋(Jquery可能会更好。)

这是我的代码:

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

我需要添加什么?

非常感谢!

3 个答案:

答案 0 :(得分:7)

首先了解document.getElementByIdsetInterval

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

答案 1 :(得分:0)

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}

答案 2 :(得分:0)

我试图将其保持在最简单的

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/