开发者

remembering a javascript var each call to function

I've got a nice little shopping basket where if the user deletes an item, the slideup jquery function is called and is disappears. In the back ground, I'm removing it from the db with a call to a code igniter controller.

function delete_booking(id_booking, amount) {
    if (user_total == null || user_total == '') {
        var user_total = parseFloat(0);
    }
    $.ajax({
        type: "POST",
        data: '',
        url: "/"+id_booking,
    });
   开发者_如何学Go $("#booking_id_"+id_booking).slideUp();
    var user_total = (parseFloat() - parseFloat() - parseFloat(user_total));

    alert(user_total);
    alert(parseFloat(user_total));
    $('#booking_total').html(user_total);
}

What I can't fathom, is when I update the user total: $('#booking_total') I need somehow to have the function remember the NEW total... I've googled 'remembering JavaScript var' and similar, but I can't find exactly what I need... My only other option is to do another call to the db with ajax to get the new total, but there MUST be a JS way to do this?


If you are not navigating to a different page, you can store the value in a variable that is outside the function (whether just on the page in the global namespace or the within the module in which the function resides).

var total;
function delete_booking(...)
{
   ...
   total = user_total;
}


as you have said

I need somehow to have the function remember the NEW total

a function cant remember a value, while a variable can, to solve your problem do one the below

1

var finalTotal;
function delete_booking(...)
{
   //your more codes
   $('#booking_total').html(user_total);
   finalTotal = user_total;
}

now variable finalTotal hold the value

2

whenever you feel that you need to access the total read this way

var total=parseint($('#booking_total').html(),10) || 0;

But think method 1 is better than method 2


Because I "hate" a global approach for this type of problem, here is a little closure which will do the job of "remembering" the value (although I'm not really sure what exactly should be saved...^^)

var delete_booking = (function() {
    var booking_total = $("#booking_total"),
        total_amount = parseFloat(booking_total.html()) || 1000; // what ever the value should be...

    return function(id, m) {
        $.ajax(/* ... */);
        $("#booking_id_"+id).slideUp();

        total_amount -= m;
        booking_total.html(total_amount);
    }
}());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜