我的学期第一个项目出了问题。使用JavaScript我应该创建一个神奇的8球模拟器。模拟器需要一个按钮,表示"摇动它"单击时,会在只读文本框中显示来自我的GetSaying()函数的随机说法。这是我有点失落的地方。我如何指定一个文本框我希望这个说法显示在哪里?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic 8 Ball!</title>
<style type="text/css">
/*Styles will go here*/
</style>
</head>
<body>
<button type="button" onclick="Show()">Shake it!</button>
<script type="text/javascript">
function Show() {
document.write(GetSaying());
}
function GetSaying() {
var pool = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Yes", "Signs point to yes",
"Reply hazy try again", "Ask again later", "Better not tell you now",
"Cannot predict now", "Concentrate and ask again", "Don't count on it",
"My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"];
return (pool[Math.floor(Math.random()*pool.length)]);
}
</script>
</body>
</html>
答案 0 :(得分:0)
您必须使用document.getElementById()
获取input
,然后设置其值。
工作示例here
<button type="button" onclick="Show()">Shake it!</button>
<input id="saying" />
<script type="text/javascript">
function Show() {
document.getElementById("saying").value = GetSaying();
}
function GetSaying() {
var pool = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Yes", "Signs point to yes",
"Reply hazy try again", "Ask again later", "Better not tell you now",
"Cannot predict now", "Concentrate and ask again", "Don't count on it",
"My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"];
return (pool[Math.floor(Math.random()*pool.length)]);
}
</script>