在javascript循环中声明变量每次单击都会为声明的变量赋值

时间:2016-01-14 09:25:06

标签: javascript jquery ajax variables loading

在javascript循环中声明变量每次单击都会为声明的变量赋予相同的值,我想在每次单击按钮时递增track_load

function loadmore() {

    var track_load = 1; //total loaded record group(s)
    var loading = false; //to prevents multipal ajax loads
    var total_groups = 5; //total record group(s)

    if (track_load <= total_groups && loading == false) //there's more data to load
    {
        loading = true; //prevent further ajax loading
        $('.animation_image').show(); //show loading image

        //load data from the server using a HTTP POST request
        $.post('autoload_process.php', {
            'group_no': track_load
        }, function(data) {

            $("#results2").append(data); //append received data into the element

            //hide loading image
            $('.animation_image').hide(); //hide loading image once data is received

            track_load++; //loaded group increment
            loading = false;

        }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?

            alert(thrownError); //alert with HTTP error
            $('.animation_image').hide(); //hide loading image
            loading = false;

        });
    }
}

HTML:

<input type="button" onClick="loadmore()" value="LOAD MORE" class="menu-button">

1 个答案:

答案 0 :(得分:1)

  

在javascript循环中声明变量...

你没有在循环中声明它。

  

我想在每次点击按钮时增加track_load

然后将loadmore函数的 out 移动到包含loadmore函数的范围中:

var track_load = 1;
function loadmore() {
    // ....
}

不幸的是,在你的情况下,这将使它成为另一个全局变量。而不是使用全局函数(全局命名空间非常拥挤),将代码包装在作用域函数中并使用现代技术挂钩处理程序,而不是onxyz属性:

&#13;
&#13;
// This goes in a script tag at the bottom of your HTML, just before
// the closing </body> tag

// Scoping function
(function() {
  $(".load-more").on("click", loadmore);
  
  var track_load = 1;
  function loadmore() {
    $("<p>").text("track_load = " + track_load).appendTo(document.body);
    ++track_load;
  }
})();
&#13;
<input type="button" value="LOAD MORE" class="menu-button load-more">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;