【问题标题】:jquery function not firing using onload event [duplicate]jquery函数未使用onload事件触发[重复]
【发布时间】:2013-12-02 21:28:13
【问题描述】:

我在这里缺少什么?我的 jquery 函数没有触发。这是 HTML:

<div id="sum_income" class="col-sm-3" onload="sumIncome();">                     

</div>

这里是 jquery 函数:

function sumIncome() {

var cur_month = $('#month option:selected').attr("value");

$.ajax({
        type: "POST",
        url: 'inc/functions.php',
        data: {action: "get_sum_income", cur_month:cur_month},
        success: function(response){
            $('#sum_income').html(response);
            setTimeout(sumIncome, 5000);
                }
    })
};

【问题讨论】:

  • 您在控制台中遇到了什么错误,请在此处写下您控制台的确切错误。
  • @NeerajKumar 他没有出错,我敢肯定。
  • @DontVoteMeDowm 我已经编写了可以正常工作的代码

标签: jquery onload


【解决方案1】:

更改您的 jquery 代码。

 $(document).ready(function(){
            if($("#sum_income").length){
                var cur_month = $('#month option:selected').attr("value");

            $.ajax({
              type: "POST",
              url: 'inc/functions.php',
              data: {action: "get_sum_income", cur_month:cur_month},
              success: function(response){
              $('#sum_income').html(response);
                 setTimeout(sumIncome, 5000);
               }
            })
          }
        });

这肯定会起作用

【讨论】:

    【解决方案2】:

    使用 $(window).onload();而不是将其添加到任何 HTML 元素中。

    <script> 
      $(window).onload(function () {
        sumIncome();
      });
    </script>
    

    【讨论】:

      【解决方案3】:

      html:

      <body onload="sumIncome();">
      </body>
      

      js:

      function sumIncome() {
      
          var m = $('#month option').val(); // assuming this is a selected tag
      
          var request = $.ajax({
              type: "POST",
              url: 'inc/functions.php',
              data: {action: "get_sum_income", cur_month:m},
              dataType: "html"
          });
          request.done(function( response ) {
              $('#sum_income').html(response);
          });
          request.fail(function( jqXHR, textStatus ) {
              alert( "Request failed: " + textStatus );
          });
          request.done(function() {
              setTimeout(sumIncome, 5000);
          })
      
      }
      

      PS:div 没有 onload 方法。

      【讨论】:

        猜你喜欢
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 2014-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        相关资源
        最近更新 更多