尝试随机选择一个短语

Coo*_*ose 3 html javascript

我试图通过创建带有Javascript函数的HTML文件来帮助婆婆,该函数将通过在chrome上打开文件并单击来为她随机选择一个短语<button>。但是,由于某种原因,它不起作用。

这是我对javascript函数的支持<head>

<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>
Run Code Online (Sandbox Code Playgroud)

然后在<body>我有:

<button type="button" onclick=myfunction(array,randInt,item,)>click me!</button>
<div id="outputdiv"></div>
Run Code Online (Sandbox Code Playgroud)

我尝试使用HTML验证程序,它说代码没有错。但是,当我加载网页时,该按钮没有任何作用。我敢肯定我缺少某个愚蠢的简单错误/修复,但是对于我一生来说,我不知道该在哪里。请帮我。提前致谢!

Nic*_*las 6

您的代码有些错误

  • 使用onclick属性永远不是一个好习惯,更好的使用document.querySelector(...).addEventListener('click', myFunction);
  • 该函数randomGenerator未定义,我已将其替换为Math.floor(Math.random() * 6)
  • 您不能使用该属性value来设置div的内部值,需要使用innerHTML
  • 您需要将randIntdiv 的值设置为在需要时显示在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);
Run Code Online (Sandbox Code Playgroud)
<button >click me!</button>
<div id="outputdiv"></div>
Run Code Online (Sandbox Code Playgroud)