Jquery .click触发身体负载

时间:2016-02-09 16:32:56

标签: javascript jquery onclick

在身体负荷上,触发按钮点击。这种行为是不需要的。导致该功能触发的原因是什么?

<!doctype html>
<html>
  <head>
  <body onload="init()">
    <div class="btn"><button type="button" class="btn" id="reset" style="font-size:60px;">Reset</button></div>
    <script>
      function init() {
      $("#reset").click(sendStatus());
    }

    // FUNCTIONS 
    function sendStatus (){
      console.log("foo");
      }
    </script>  
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

您在init函数中有一个click事件。您正在body标签的onload属性中调用该函数。

答案 1 :(得分:0)

您的代码几乎没有根本问题。

  1. 没有document.ready函数。请使用此而不是onload。请参阅以下链接以了解其中的差异。
  2. window.onload vs $(document).ready()

    jQuery - What are differences between $(document).ready and $(window).load?

    1. 在init函数按钮单击事件中,您正在调用函数&#34; sendStatus&#34;而不是分配它。因此它会立即被触发
    2. 我修改了以下代码

       $(function() {
      
         function init() {
           $("#reset").click(sendStatus);
         }
      
         // FUNCTIONS 
         function sendStatus() {
           console.log("foo");
         }
      
           init();
      
       });
      

      这里是小提琴。 https://jsfiddle.net/7nt4q6yt/1/