我试图通过创建一个带有 Javascript 功能的 HTML 文件来帮助我的岳母,该文件将通过在 chrome 上打开文件并单击 <button>
为她随机选择一个短语。 .但是,由于某种原因,它不起作用。
这是我在 <head>
中的 javascript 函数的内容:
<script>
myfunction(array,randInt,item,){
var array = ["phrase here", "here", "and here"];
var randInt = randomGenerator(0, array.length-1);
var item = array[randInt];
document.getElementById('outputdiv').value = randInt;
}
</script>
然后在
<body>
我有:<button type="button" onclick=myfunction(array,randInt,item,)>click me!</button>
<div id="outputdiv"></div>
我尝试使用 HTML 验证器,它说代码没有任何问题。但是,当我加载网页时,该按钮不执行任何操作。我确定我遗漏了一些愚蠢的简单错误/修复,但对于我的生活,我无法弄清楚在哪里。请帮我。提前致谢!
最佳答案
您的代码有一些问题
onclick
从来都不是一个好习惯属性,更好用document.querySelector(...).addEventListener('click', myFunction);
randomGenerator
未定义,我已将其替换为 Math.floor(Math.random() * 6)
value
要设置 div 的内部值,您需要使用 innerHTML
randInt
的值作为在你的 div 中显示的内容,当你需要它时 item
. function
在它面前。 我在这里创建了一个工作版本的片段:
function func() {
var array=["phrase here", "here", "and here"];
var randInt= Math.floor(Math.random() * array.length)
var item=array[randInt];
document.getElementById('outputdiv').innerHTML=item
}
document.querySelector('button').addEventListener('click', func);
<button >click me!</button>
<div id="outputdiv"></div>
关于javascript - 尝试随机选择一个短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58844054/