在getData()上,我使用ajax get请求拉一些li并将它们附加到容器中。成功执行ajax调用后,我创建了一个名为next_load的变量,该变量获取数据属性并将其作为下一个get数据调用的url传递。我的问题是,在第二次单击时,调用上有一个累积的变量。在控制台中,我可以看到第一个日期也和第二个日期一起传递。目标是在页面加载中获得第一个日期。然后单击该框以获取下一个日期,依此类推。

HTML:

<div id = "calendar">
                <div class = "box">
                    <ul class = "label">
                        <li>Sun</li>
                        <li>Mon</li>
                        <li>Tue</li>
                        <li>Wed</li>
                        <li>Thur</li>
                        <li>Fri</li>
                        <li>Sat</li>
                    </ul>
                </div>
                <ul class = "box-content">

                </ul>
    </div>


在控制台中:

    2 calendar.js:34 2016-03-05 -> on the first get, then this and the next on the second get and it keeps building up.
calendar.js:34 2016-04-09



   function getData(url) {
    var next_load = '';
    $.ajax({
        url: 'student/calendar/' + url,
        type: 'GET',
        success: function(response) {
            var $result = $(response).filter('li');
            $('.box-content').append($result);

            next_load = $result.last().attr('data-date');
            useNextLoad(next_load); // dont use the value till the ajax promise resolves here

        }
    })
}
getData('show/2016/02');

function useNextLoad(next_load){
    var load = next_load;
    $('.box').click(function(){
       getData('load/' + load);
        console.log(load); // when i pass the next_load Im getting the previous next load and the new next load at the same time. Then on the next click the amount compounds.
    });

}


如果我重置变量next_load,可以阻止构建?我尝试在ajax调用之前清空变量,但仍然可以建立该变量。

最佳答案

将click函数多次应用于.box可能是一个问题。您可能需要从.box删除任何现有的单击处理程序,然后再绑定新的处理程序。见How to remove all Click event handlers in Jquery

function useNextLoad(next_load){
var load = next_load;
 $('.box').off("click");  // Remove any click handlers already on .box
$('.box').click(function(){
 ...


当然,如果您想更紧凑,也可以在jQuery中链接您的调用。

07-24 18:14
查看更多