jQuery 单击按钮无效

jQuery wont work with click on a button

我遇到了一个无法解决问题的问题!我只是想在我的控制台中显示 'test' 以查看我的选择器是否有效。我注释掉了它周围的一切,整个脚本,除了选择器,但它仍然不起作用。我是 jQuery 的新手,所以也许我的实现有误?这是我的代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">

    $('#find').on("click", function(){
        console.log("test");
    });

</script>
</head>
<body>
    <p>Postleitszahl:</p>
    <input type="number" autocomplete="on" name="inp" class="inp">
    <button type="button" id="find">Finden</button>
    <p class="outp"></p>
</body>
</html>

试试下面的代码。它现在应该可以工作了。

$('#find').click(function() {
  alert('button clicked!');
  console.log('test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>Postleitszahl:</p>
    <input type="number" autocomplete="on" name="inp" class="inp">
    <button type="button" id="find">Finden</button>
    <p class="outp"></p>

你可以使用这个有效的代码!

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $('#find').on("click", function(){
       alert("test");
       console.log("test");
    });
});
</script>
</head>
<body>

<p>Postleitszahl:</p>
    <input type="number" autocomplete="on" name="inp" class="inp">
    <button type="button" id="find">Finden</button>
    <p class="outp"></p>

</body>
</html>

您可以将包含函数的 script 块移动到 body:

的底部

<!-- other code -->

<script type="text/javascript">
    $('#find').on("click", function(){
        console.log("test");
    });
</script>

或者您可以在 head 中使用 $(document).ready(),如下所示:

<!-- other code -->

<script type="text/javascript">

    $(document).ready( function() {
      $('#find').on("click", function(){
          console.log("test");
      });
    })

</script>

原因是 javascript 在将元素加载到 DOM 之前无法识别这些元素。

您可以在 here 中找到有关加载脚本的更多信息。