来自外部脚本的按钮调用 ID

Button calling ID from External Script

本文关键字:按钮 调用 ID 脚本 外部      更新时间:2023-09-26

我正在尝试编写一个在单击按钮时调用外部.js脚本的游戏。代码按照我想要的方式工作,但我对如何将输出转换为 HTML 以便可以正确格式化有点困惑。每当单击按钮时,该按钮都应重新启动该过程(即无需重新加载页面(,以便进行新的随机选择。

我最终还想包含一个按钮来删除最后显示的项目,但那是以后的事情......

Javascript:

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
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); }, 3000); 
//stop display after x milliseconds

当前的 HTML 显然运行代码,但它在单击按钮之前启动。

.HTML:

<head><script type="text/javascript" src="Fruitpicker3.js"></script></head>
<body>
<span id = "fruit"> </span>
<input type="button" onclick="fruit" value="Start"/>
</body>
</html>

提前感谢您的帮助!

您的setInterval调用不在函数内部,因此当下载并执行.js文件时,它会立即执行该方法。最简单的解决方案是将 setInterval 调用包装在函数内部,然后在按钮的 onClick 事件中调用该函数。