为什么变量没有在我的事件处理程序中重置?

时间:2021-01-28 23:59:37

Here's my code:

这是我的代码:

$(document).ready(function () {
    var default_var = 2;
    var show_var = default_var;
    var total_var = 8;
    var increment_var = 2;


    var start_var = show_var+1;
    var end_var = show_var+increment_var;

    $("a[rel=more]").live("click", function(){

        $("#timeshare-listings li:last").after("<li class='ajax'></li>");
        $("#timeshare-listings li.ajax").load("http://www.goodbuytimeshare.com/listings/ajax/"+start_var+"/"+end_var+"/");
        $("#timeshare-listings li.ajax").removeClass("ajax");

        var show_var = end_var+1;

        return false;
    });
});

The first time I click the button it does exactly what I want. Unfortunately, for some reason, show_var never changes its value. Why not? What do I have to do to make it change?

我第一次点击按钮,它完全符合我的要求。不幸的是,由于某种原因,show_var永远不会改变它的价值。为什么不?我需要做些什么来改变它?

1 个解决方案

#1


 ...
var show_var = default_var;
 ...

$("a[rel=more]").live("click", function(){
     ...
    // declares and initializes entirely new variable named show_var 
    // that will never be used again...
    var show_var = end_var+1;
     ...
});

You're re-declaring show_var in the handler for the live click event. Don't do that - just reference the one in the outer scope, and it should do what you want...

您在实时点击事件的处理程序中重新声明了show_var。不要这样做 - 只引用外部范围中的那个,它应该做你想要的...

 ...
var show_var = default_var;
 ...
$("a[rel=more]").live("click", function(){
    ...
    show_var = end_var+1; // update value in outer scope
    ...
});

#1


 ...
var show_var = default_var;
 ...

$("a[rel=more]").live("click", function(){
     ...
    // declares and initializes entirely new variable named show_var 
    // that will never be used again...
    var show_var = end_var+1;
     ...
});

You're re-declaring show_var in the handler for the live click event. Don't do that - just reference the one in the outer scope, and it should do what you want...

您在实时点击事件的处理程序中重新声明了show_var。不要这样做 - 只引用外部范围中的那个,它应该做你想要的...

 ...
var show_var = default_var;
 ...
$("a[rel=more]").live("click", function(){
    ...
    show_var = end_var+1; // update value in outer scope
    ...
});