jQuery 事件处理程序在此代码中不起作用

jQuery event handler does not work in this code

我目前无法使用 jQuery 使此代码正常工作。当我将它专门添加到 "a" link 元素时,同样的事件起作用。我希望 jQuery 注册一个警报,以便在单击 link 时显示,但当我单击 link 时没有任何反应。我是 运行 这个 html 在 Chrome 并且 DevTools 控制台根本没有显示任何错误!我不确定我会做错什么,因为我只是按照这本书做的!总的来说,我已经看到 jQuery 对任何东西都不起作用 javascript 但我已经发布了这段小代码来说明。感谢任何帮助找出我可能做错了什么!

<html>

<head>
  <!-- jQuery version 3.3.1 -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />
  <script>
    $(document).ready(function() {
      $("a").click(function() {
        //This should show an alert when any link on the page is clicked.
        alert("This is a test");
      })
    });
  </script>
</head>

<body>
  <a href="#">Click here to see alert</a>
  <!-- This does not work! -->
  <!-- This works fine!
                <a href="#" onclick="javascript:alert('This is a test');">Click here to see alert</a> -->
</body>

</html>

问题是因为 script 标签不是自动关闭的。您需要在 jQuery.js 引用后添加一个单独的 </script> 标签:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("a").click(function() {
        console.log("This is a test");
      })
    });
  </script>
</head>
<body>
  <a href="#">Click here to see alert</a>
</body>
</html>

您的 onclick="javascript:alert('This is a test');" 仍然有效的原因是因为它不依赖于对 jQuery 的损坏引用。

也就是说,您应该避免使用 on* 事件属性,因为它们已经过时了。到目前为止,不显眼的事件处理程序是最佳实践。