开发者

jQuery remove multiple last items on .each iteration

开发者 https://www.devze.com 2023-02-21 02:44 出处:网络
I am having trouble removing the last DD and DT tags from a definition list when prepending new content using .each. My goal is to remove a set of DD and DT tags with each iteration (as new DD and DT

I am having trouble removing the last DD and DT tags from a definition list when prepending new content using .each. My goal is to remove a set of DD and DT tags with each iteration (as new DD and DT tags are prepended). The following is example code I am using:

shouts_list = $("#shouts dl#shouts_list");
$.each(json.shouts, function (id, shout) {
            $("<dt>" + shout.name + "</dt><dd>" + shout.message +  "</dd>").hide().prependTo(shouts_list).s开发者_StackOverflow社区lideDown('slow', 'swing', function() {
            $("#shouts_list > dt:last, #shouts_list > dd:last").slideUp('slow', 'swing');
            }).fadeIn();
        });

Each time my json object contains multiple items, only one set of DT and DD are removed from the end.

I am learning jQuery and JavaScript slowly and have been stuck on this issue for a while. What would be a good way to remove items from the end of the list for each iteration?


Only one element is being removed from the list because the each loop is going through all the items in json.shouts before the first slideUp call finishes (ie the loop is too fast or slideUp is too slow). This means that each time this executes:

$("#shouts_list > dt:last, #shouts_list > dd:last").slideUp('slow', 'swing');

the original last item in the list is always being found, so you're actually calling slideUp on the same element json.shouts.length number of times. You need to get all the original items in the list before the each loop starts and count backwards to remove one for each new item added.

This should do the trick:

shouts_list = $("#shouts dl#shouts_list");
var existingDts = shouts_list.find("> dt");
var existingDds = shouts_list.find("> dd");

$.each(json.shouts, function (id, shout) {
     $("<dt>" + shout.name + "</dt><dd>" + shout.message +  "</dd>")
       .hide().prependTo(shouts_list)
       .slideDown('slow', 'swing', function() {
           $(existingDts[existingDts.length - 1 - id]).slideUp('slow', 'swing');
           $(existingDds[existingDds.length - 1 - id]).slideUp('slow', 'swing');
     })
    .fadeIn();
});
0

精彩评论

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