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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15691972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:43:40  来源:igfitidea点击:

Only display one array item at a time (Javascript)

javascriptarraysloops

提问by Isaac Nelson

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

我试图从本质上创建一个股票代码,它显示一次从数组中获取的单个字符串项目。基本上我只是想让它显示一个项目,然后过渡到下一个项目,我的 Javascript 技能非常初级(Jquery 可能更适合这个。)

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!

谢谢一堆!

回答by Trevor Dixon

Start by learning about document.getElementByIdand setInterval.

从学习document.getElementById和开始setInterval

http://jsfiddle.net/wtNhf/

http://jsfiddle.net/wtNhf/

HTML:

HTML:

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

Javascript:

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

回答by James Daly

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

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

js

js

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

html

html

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

css

css

 span {display:none}

回答by bgusach

I tried to keep it at its simplest

我试图让它保持最简单

HTML

HTML

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

Javascript

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/

http://jsfiddle.net/zTLqe/