我希望能够取出定时事件的结果,但我不知道如何找到它的索引。问题是我按时间从数组中选择一个项目,但是按索引号选择,所以我需要能够在计时器运行后得到结果。
这将是
mixedgroup1.splice(i, 1);
其中i是最终结果的索引号,但我不知道如何得到它。
有什么想法吗?
这是JS代码:
var basket = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig', 'grapes', 'huckleberry', 'kiwi', 'lemon', 'mango'];
function randOrd(){
return (Math.round(Math.random())-0.5); }
mixedBasket = basket.sort( randOrd ); //randomize the array
var i = 0; // the index of the current item to show
function showBasket(){
fruitDisplay = setInterval(function() {
document
.getElementById('fruit')
.innerHTML = mixedBasket[i++]; // get the item and increment
if (i == mixedBasket.length) i = 0; // reset to first element if you've reached the end
}, 70); //speed to display items
var endFruitDisplay = setTimeout(function( ) { clearInterval(fruitDisplay); }, 3600);
//stop display after x milliseconds
}
这是HTML:
<html>
<head></head>
<body>
<center>
<h1> <span id="fruit"></span><p></h1>
<script> var fruitSound = new Audio();
fruitSound.src = "boardfill.mp3";
function showFruitwithSound()
{
fruitSound.play(); // Play button sound now
showBasket()
}
</script>
<button onclick="showFruitwithSound()">Choose Fruit</button>
</center>
<script type="text/javascript" src="Fruitpicker3.js"></script>
</body>
</html>
答案 0 :(得分:0)
以下是如何获得最终结果的索引:
mixedBasket.indexOf(document.getElementById('fruit').innerHTML);
在此处添加:
var endFruitDisplay = setTimeout(function( ) {
clearInterval(fruitDisplay);
var index = mixedBasket.indexOf(document.getElementById('fruit').innerHTML);
//do splice and stuff
document.getElementById("indexnum").innerHTML = index;
}, 3600);
答案 1 :(得分:0)
很抱歉这么密集,但我对js相当新。我根本无法获得任何输出。这是重写:
<center>
<h1> <span id="fruit"></span><p></h1>
<script> var fruitSound = new Audio();
fruitSound.src = "boardfill.mp3";
function showFruitwithSound()
{
fruitSound.play(); // Play button sound now
showBasket()
}
</script>
<p id = "indexnum">
<button onclick="showFruitwithSound()">Choose Fruit</button>
</center>
<script>
var indexf = mixedBasket.indexOf(document.getElementById('fruit').innerHTML);
document.getElementById("indexnum").innerHTML = indexf + " this is the index number.";
</script>
<script type="text/javascript" src="Fruitpicker3.js"></script>
</body>