jquery函数没有使用onload事件触发

时间:2013-12-02 13:13:24

标签: jquery onload

我在这里缺少什么?我的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);
                }
    })
};

3 个答案:

答案 0 :(得分:3)

更改您的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);
               }
            })
          }
        });

这将绝对有效

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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方法。

相关问题