我试图通过创建带有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验证程序,它说代码没有错。但是,当我加载网页时,该按钮没有任何作用。我敢肯定我缺少某个愚蠢的简单错误/修复,但是对于我一生来说,我不知道该在哪里。请帮我。提前致谢!
您的代码有些错误
onclick属性永远不是一个好习惯,更好的使用document.querySelector(...).addEventListener('click', myFunction);randomGenerator未定义,我已将其替换为Math.floor(Math.random() * 6)value来设置div的内部值,需要使用innerHTMLrandIntdiv 的值设置为在需要时显示在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)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |