javascript - jQuery 仅删除第一个 div 一次

标签 javascript jquery ajax

我有一个函数:

function removeDiv() {          
    var topmost = jQuery('.xx');
    var totContent = topmost.find('.zz').length;
    var $target = jQuery('.xx').find('.zz').eq(0);
    if(totContent > 5) {
        $target.hide('slow', function(){ $target.remove(); });
    }
}

我在我的 ajax 调用中使用它,删除多余的 div 然后有超过 5 个,hovewer 它只删除第一个 div 一次!

这是 ajax 调用的样子:

function saveClubs(array) {
    for(i=0; i<array.length; i++) {
    var id = array[i];
        jQuery.ajax({
            type: "GET",
            async: true,
            url: 'index.php?option=com_events&task=club.save&id=' + id,
            dataType: 'json',
            success: function(data) {
                jQuery('.xx').append('<div class="zz">'+data+'</div>');
                removeDiv();
            }
        });
    }
}

有什么想法吗?

最佳答案

这是 Paul Roub 的回答,作为回答而不是 comment 发布:

可能的问题是,由于您在循环中进行了一堆 ajax 调用,它们往往会同时完成,因此您最终会重复淡出相同元素(因为它仍然存在,直到它完成褪色)。

最小的更改 解决方法是,比如说,在您淡出它时添加一个类:

function removeDiv() {
    // Get the container (I take it there's only one .xx element)
    var topmost = jQuery('.xx');

    // Get the child elements that aren't fading
    var zz = topmost.find('.zz').not('.fading');

    // Too many?
    if(zz.length > 5) {
        // Yup, add 'fading' to the first one and fade it out
        // Note that there's no need for the $target variable
        zz.eq(0).addClass('fading').hide('slow', function(){ $(this).remove(); });
    }
}

关于javascript - jQuery 仅删除第一个 div 一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489700/

相关文章:

jQuery Masonry 与 jQuery UI Sortable 冲突

javascript - 在 DOM 中向上移动步骤

javascript - 使用 angularjs 的货币转换器

javascript - 如何减少对每个空选择使用错误消息

javascript - Webpack 更改特定包的导入路径

javascript - 如何在多个标记之间制定路线方向

javascript - 使用 jQuery UI 消失带有模态消息的元素

javascript - 为什么访问 Ajax 响应变量会导致代码崩溃?

php - "invite friends via email"功能...我应该关注哪些安全隐患?

php - 当 readyState 为 4 时,为什么我在脚本中调用的 Ajax 函数会连续运行两次?