1

I update three inputs in a row, they are updated sequentially via a single button click and I do a cool color change (glowing) effect to each input after completion of updating:

You should see something like this where t= time (i feel like a scientist)

    [30.20]  [20.32]  [34.33]  [Update] <--- Clicked this
t=1 Glow
t=2          Glows     
t=3                   Glows

but sometimes the color effect goes out of order like:

    [30.20]  [20.32]  [34.33]  [Update] <--- Clicked this
t=1 Glow
t=2                   Glows
t=3          Glows     

Here is my script:

FYI: i tested and found that the out of sequence issue begins on the .each

On the page they are one after the other.

function UpdatePrice(TheButton, Type) {
    $(TheButton).parent().parent().find("input").each(function (index, element) {

        $.ajax({
            cache: false,
            data: { ByContractID: $(element).parent().attr("id"), Cost: $(element).val(), ItemType: Type },
            type: "Post",
            url: '@Url.Action("UpdateCost")'
        }).success(function () {

            $(element).next().html(($(TheButton).parent().parent().children("td").eq(0).html() * $(element).val()).toFixed(2));
            $(element).val(parseFloat($(element).val()).toFixed(2));
            var old = $(element).css('background-color');
            $(element).animate({ "background-color": "#D2F0C9" }, "fast", function () { $(element).animate({ "background-color": old }, "fast") });


        });


    });

    return false;
}

What do y'all think?

Thanks!

4

2 回答 2

2

您正在执行 ajax 请求,每个请求可能需要不同的时间......由于 ajax 是异步的,它们都同时执行,哪个首先返回第一个输出,等等。

于 2013-07-11T19:42:23.810 回答
2

Queue尝试在我的答案中使用like ,然后您可以执行以下操作

function UpdatePrice(TheButton, Type) {
    var q = new Queue;
    $(TheButton).parent().parent().find("input").each(function (index, element) {
        //add to the Queue
        q.add(function(){
            $.ajax({
                cache: false,
                data: { ByContractID: $(element).parent().attr("id"), Cost: $(element).val(), ItemType: Type },
                type: "Post",
                url: '@Url.Action("UpdateCost")'
            }).success(function () {

                $(element).next().html(($(TheButton).parent().parent().children("td").eq(0).html() *     $(element).val()).toFixed(2));
                $(element).val(parseFloat($(element).val()).toFixed(2));
                var old = $(element).css('background-color');
                $(element).animate({ "background-color": "#D2F0C9" }, "fast", function () {     $(element).animate({ "background-color": old }, "fast") });

                q.next(); //run next function

            });

            return false; 
            // ^^ insures that the queue does not continue when the function is finished.
        });

    });

    return false;
}

之所以必须这样做,是因为 Ajax 是异步的,所以为了按顺序运行它们,必须在上一个调用完成运行新的 ajax 调用。

于 2013-07-11T19:43:16.233 回答