单击按钮时,我试图显示头部或尾部。我不知道我哪里出错了。这似乎是一件非常简单的事情,但也许我错过了一些东西?这就是我所拥有的。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9</title>
<link href="images/avatar.png" rel="shortcut icon" type="image/png">
<link href="css/stylesheet.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" type="text/javascript"></script>
<style type="text/css">
.auto-style1 {
text-align: center;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<header>
</header>
<aside>
</aside>
<div id="main">
<h1> Arrays and Coditional Statements</h1>
<h2 class="auto-style1"> Quote of the Day</h2>
<h2 class="auto-style1">Flip a coin </h2>
<script>
<script>
function myFunction1{
var x =Math.floor(Math.random()*2);
if ( x==0){
document.getElementById("Coin").innerHTML= "Heads";
}
else{
document.getElementById("Coin").innerHTML= "Tails";
}}
myFunction1();
</script>
<button type="button" onclick="myFunction1" id="Coin"> CLick ME</button>
</div>
<footer>
</footer>
</body>
</html>
答案 0 :(得分:1)
()
myFunction1
答案 1 :(得分:1)
您没有在onclick
属性中调用该函数,而只是命名它。通过在函数名后添加()
(括起参数)来调用函数。所以它应该是
onclick="myFunction1()"
答案 2 :(得分:0)
以下是解决方案:
作业9 .auto-style1 { text-align:center; }
<h2 class="auto-style1"> Quote of the Day</h2>
<h2 class="auto-style1">Flip a coin </h2>
CLick ME
myFunction1();
function myFunction1() {
var x =Math.floor(Math.random()*2);
if ( x==0){
document.getElementById("Coin").innerHTML= "Heads";
}
else{
document.getElementById("Coin").innerHTML= "Tails";
}
}
</div>
<footer>
</footer>
</body>
</html>
答案 3 :(得分:0)
一些事情:
script
标记
()
来电时需要onclick
- onclick="myFunction1()"
()
:function myFunction1() {
myFunction1()
时,您的Coin
元素尚不存在 - 将脚本放在元素的创建之后,或者一个window.onload
处理程序。将这些修补程序放在一起:
<button type="button" onclick="myFunction1()" id="Coin">CLick ME</button>
<script>
function myFunction1() {
var x = Math.floor(Math.random() * 2);
console.log(x);
if (x == 0) {
document.getElementById("Coin").innerHTML = "Heads";
} else {
document.getElementById("Coin").innerHTML = "Tails";
}
}
myFunction1();
</script>
&#13;
当你解决这些问题时,JavaScript console会一个接一个地告诉你这些问题。我建议熟悉它。
答案 4 :(得分:0)
您可以使用这行JavaScript来获取heads
或tails
console.log(Math.floor(Math.random() * 2) === 1 ? "heads" : "tails")