当我单击停止按钮时,预输入一个特定的数组元素



我在一个数组中重复循环,我的目标是停止循环并打印出数组中的特定元素,并通过span id="水果";。请参阅下面的代码:

var title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
document
.getElementById('fruit')
.innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

您的意思是

const title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
const winner = title[3]; // for example
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
document
.getElementById('fruit')
.innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
document
.getElementById('fruit')
.innerHTML = winner;
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

var title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
//document.getElementById('fruit').innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
document.getElementById('fruit').innerHTML = title[i++];
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

这个怎么样?

我把数字改成了水果,因为。。好我只是想写一些水果。但它们可以改回c的数字。

var fruits = ['Apple', 'Banana', 'Pineapple', 'Orange', 'Kiwi', 'Watermelon'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
i++
document
.getElementById('fruit')
// use modulus operator to stay inside array
.innerHTML = fruits[i % fruits.length];
}, 15);
function stop() {
clearInterval(animate);
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

最新更新