为什么在我按开始时我的 console.log 消息没有显示?

Why doesn't my console.log message show when I press Start?

我正在学习使用事件侦听器,我想将 "Start" 按钮的按下记录到控制台以确保该按钮有效,但我在测试 [=13] 时没有得到任何结果=] devtools 中的文件。

JAVASCRIPT:

function startQuiz() {
    $('#startButton').click(function(event){
        console.log("Keep Going");
    });
}

HTML:

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Herbal Medicine: Adaptogens</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="questions" href="store.html">
</head>
<body>
    <div class="container">
        <p>Intro to Herbal Adaptogens explaining what they are</p>
        <button id="startButton">Start</button>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="index.js"></script>
</body>
</html>

我希望在我按下 "start" 时在控制台中看到 "Keep Going",但实际上什么也没有发生。

您在 startQuiz() 函数中有 JQuery click() 函数。所以它不会工作,除非外部函数(startQuiz())首先是运行。您应该将它放在一个就绪函数中,以便在页面 'ready'.

时加载

将您的 javascript 更改为如下所示:

$(document).ready(function() {
    $('#startButton').click(function(event) {
        console.log("Keep Going");
    });
});

您应该将它放在 Jquery 点击函数中。这样它就会在文档加载时触发。

$(document).ready(function() {
    $('#startButton').click(function(event) {
        console.log("Keep Going");
    }
});

不用jQuery,直接用js事件即可。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Log Window</title>
</head>
<body>
  <script>
  function logMe() {console.log('clicked');}
  </script>
  <button onclick="logMe()">logMe</button>
</body>
</html>