javascript - 尝试随机选择一个短语

标签 javascript html

我试图通过创建一个带有 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/

    相关文章:

    javascript - ng-if 不起作用,但 ng-show 起作用

    javascript - 我如何更改c3饼图中的图例文本

    HTML 和 CSS : placing the Google +1 button makes it impossible to add space between elements

    javascript - 来自 javascript 对象的 @Html.Partial 期间未终止的字符串常量

    javascript - 如何显示指示平均值的进度条

    javascript - 使用 javascript HotRuby.js 时,Ruby 代码在哪里编译?

    javascript - 如何根据数组porp的值查找数组中的元素

    PHP 邮件();以纯文本和 HTML 格式发送电子邮件

    javascript - 溢出不包含 div 内容

    javascript - 克隆和删除列表项,但如果是该项目,则阻止删除第一个