0

我有以下 JQuery,它允许用户选择/取消选择项目/价格列表作为创建自动报价的一种方式。代码如下所示:

$('table.products > tbody > tr').click(function(){
    if ($(this).find('div.price').is(":visible")) {
        $(this).find('div.price, img.selected').fadeOut(100);
    } else {
        $(this).siblings('div.price, img.selected').fadeIn(100);                    
    }
    recalc();
});

它实际上比这更复杂(因此我没有使用的原因,toggle()但以上只是这个问题的简化示例。

无论如何,上面的代码工作正常。如果单击表格行,则选择/取消选择价格和图像,具体取决于价格是否已经显示。

然后我调用了一个recalc();最后调用的函数。它看起来像这样(同样,这是一个简化版本):

function recalc() {
    var numOfProducts = $('table.products div.price:visible').length;
    alert(numOfProducts);
}

我在这里遇到的问题是警报总是返回在任何更改之前都是正确的值。

例如,如果没有div.price可见并且我选择了一个,则一个将变为可见但警报显示0。然后,如果我选择另一个,这会使 2 可见,但仅显示警报1,因为这就是我单击时的样子。如果我然后单击我已经单击的项目之一以取消选择它,它将显示2

所以,我的问题是我应该如何确保函数调用在其他所有事情都完成之后发生?

4

2 回答 2

1

这是因为recalc()在动画完成之前被调用,因此元素仍然可见。

你有两个选择。首先是摆脱动画:

$('table.products > tbody > tr').click(function(){
    if ($(this).find('div.price').is(":visible")) {
        $(this).find('div.price, img.selected').hide();
    } 
    else {
        $(this).siblings('div.price, img.selected').show();                    
    }
    recalc();
});

The second is to call recalc() in the callback of each fade, so that it happens after the animation is complete:

$('table.products > tbody > tr').click(function(){
    if ($(this).find('div.price').is(":visible")) {
        $(this).find('div.price, img.selected').fadeOut(100, recalc);
    }
    else {
        $(this).siblings('div.price, img.selected').fadeIn(100, recalc);                    
    }        
});
于 2012-05-29T09:26:15.057 回答
0

I have come to the conclusion that my approach is completely wrong. I'm basing this partly on the fact that not many people have suggested answers to this question and also partly because the answers I have received don't accomplish what I'm trying to do. Perhaps my explanation wasn't clear enough, too.

So, my solution to my original question of getting an accurate report of the number of selected product rows is to create a global variable in JS as so:

window.config =
    {
        products : 0,
    };

Then, add lines to the if statement to increment or decrement the variable depending on what happened:

$('table.products > tbody > tr').click(function(){
    window.config.products = window.config.products - 1; // Decrement
    if ($(this).find('div.price').is(":visible")) {
        $(this).find('div.price, img.selected').fadeOut(100);
    } else {
        window.config.products = window.config.products + 1; // Increment
        $(this).siblings('div.price, img.selected').fadeIn(100);                    
    }
});

Now I have an accurate record of the number of selected products in the global variable which I can access at any time to continue the development of my application.

于 2012-06-01T03:40:16.277 回答