我正在尝试创建一个HTML脚本,该脚本将从有人加载页面时给出的列表中选择一个随机数。这意味着如果他们刷新页面,则会出现一个新数字。我知道如何生成一个脚本,当你按下按钮时显示一个随机的单词/数字,但是必须让数字自己生成,而且它不能出现在wordbox中。如果有人可以帮助我,我会很感激。
我对编码知之甚少,但从我收集到的信息来看,这就是我构建的内容:
<html>
<head>
<title></title>
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of random words
var NumberOfWords = 32
var words = new BuildArray(NumberOfWords)
// Use the following variables to
// define your random words:
words[1] = "2,719"
words[2] = "2,718"
words[3] = "2,717"
words[4] = "2,715"
words[5] = "2,713"
words[6] = "2,711"
words[7] = "2,710"
words[8] = "2,709"
words[9] = "2,708"
words[10] = "2,706"
words[11] = "2,704"
words[12] = "2,702"
words[13] = "2,701"
words[14] = "2,700"
words[15] = "2,699"
words[16] = "2,698"
words[17] = "2,696"
words[18] = "2,694"
words[19] = "2,692"
words[20] = "2,690"
words[21] = "2,688"
words[22] = "2,686"
words[23] = "2,685"
words[24] = "2,683"
words[25] = "2,681"
words[26] = "2,678"
words[27] = "2,675"
words[28] = "2,673"
words[29] = "2,671"
words[30] = "2,669"
words[31] = "2,667"
words[32] = "2,664"
function BuildArray(size){
this.length = size
for (var i = 1; i <= size; i++){
this[i] = null}
return this
}
document.addEventListener("DOMContentLoaded",
function PickRandomWord(frm) {
// Generate a random number between 1 and NumberOfWords
var rnd = Math.ceil(Math.random() * NumberOfWords)
// Display the word inside the text box
frm.WordBox.value = words[rnd]
})
//-->
</SCRIPT>
<CENTER>
<FORM NAME="WordForm">
<INPUT TYPE=TEXT SIZE=50 NAME="WordBox"><BR>
</CENTER>
</FORM>
<body>
<big><big><span style="font-weight: bold;">
<br>
<br>
<br>
</span></big></big>
</body>
</html>
问题是它不起作用而且我不知道为什么。
答案 0 :(得分:0)
您应该将脚本放在DOMContentLoaded侦听器中:
document.addEventListener("DOMContentLoaded", function() {
//call your script here
});
注意:IE8 does not support addEventListener。
如果您使用的是jquery
,则可以使用$(document).ready
$(document).ready(function() {
//call your script here
});