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

问题描述 投票:1回答:1

我目前无法使用jQuery使用此代码。当我在“a”链接元素上专门添加它时,同样的事件也有效。我希望jQuery能够在点击链接时注册一个警告,但是当我点击该链接时没有任何反应。我在Chrome中运行这个html,而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>
jquery events click
1个回答
1
投票

问题是因为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*事件属性,因为它们已经过时了。不引人注意的事件处理程序是目前最好的做法。

© www.soinside.com 2019 - 2024. All rights reserved.