Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

jQuery variable isn't updating after ajax execution

I have a load more button, that each time I clicked should show 10 new results, but the offset value isn't updating so it is always showing me the same 10 results

$("#loadmore_timeline").on("click",function(e){ // When btn is pressed.
        e.preventDefault();
        $number = 10;
        $offset = $number;
        $("#loadmore_timeline").attr("disabled",true); // Disable the button, temp.
        $.ajax({
            url: jx.ajaxurl,
            method: "POST",
            cache : false,
            data:{
                "action": 'more_timeline_activities_ajax',
                "number": $number,
                "offset": $offset
            },
            success: function(data){
                $("table.activity_timeline").append(data.content);
                $offset = $offset + 10;
                $("#loadmore_timeline").attr("disabled",false);
                console.log($offset);
            },
            error: function(error) {
                console.log('error:', error);
            }
        });
    });

I think it's happening because the number value is constant and it's the value that uses as a reference, but I don't know how to get and update this value in a different place.

question from:https://stackoverflow.com/questions/65602487/jquery-variable-isnt-updating-after-ajax-execution

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So move the varaibles

$number = 10;
$offset = $number;

outside of the click event so you are not overriding them on every click.

var $number = 10;
var $offset = $number;
$("#loadmore_timeline").on("click",function(e){ // When btn is pressed.
    e.preventDefault();
    $("#loadmore_timeline").attr("disabled",true); 
    ...
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...