JS 无法使事件监听器工作
2017-03-04
70
有人能告诉我这段代码有什么问题吗?我无法让它工作。 我试图让这个按钮可点击,但它一直给出错误: 未捕获的语法错误:无效或意外的令牌
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="Stylesheet" href="../CSS/Reset.css" type="text/css">
<link rel="Stylesheet" href="../CSS/style.css" type="text/css">
<meta charset="UTF-8">
<title>Psychic Game</title>
</head>
<body>
<script src="../JS/Javascript.js" type="text/javascript">
</script>
<button id="myBtn"> A </button>
<h1> Psychic Game </h1>
<h3> Guess what letter im thinking of </h3>
<h3> Wins: </h3>
<h3> Losses: </h3>
<h3> Guesses Left: </h3>
<h3> Your Guesses so far: </h3>
JS:
var computerChoice = letterBank[Math.floor(Math.random() * letterBank.length)];
function log() {
console.log(computerChoice);
}
//document.getElementById("myBtn").addEventListener("click", function(){console.log("computerChoice")});
document.getElementById("myBtn").addEventListener("click", function(){console.log("computerChoice")});
3个回答
您应该将 script.js 文件的声明移到您所引用的实际 DOM 元素下方。
因此您的 HTML 应如下所示:
<body>
<button id="myBtn"> A </button>
<script src="../JS/Javascript.js" type="text/javascript">
</script>
<h1> Psychic Game </h1>
egor kurnev
2017-03-04
尝试一下
document.getElementById('demo').addEventListener('click', function(){
alert('clicked')
})
<button type="button" id='demo'>Click Me!</button>
document.getElementById('demo').addEventListener('click', function(){
alert('clicked')
})
<p id="demo">Click me</p>
Abhishek Kumar Pandey
2017-03-04
你最好先学习一下js。 应该是:
document.getElementById("myBtn").addEventListener("click", function(){console.log("computerChoice")});
blackmiaool
2017-03-04