简体   繁体   中英

jquery append remove and append

I am trying to display 4 objects at a time, but somehow it displayed all the objects. In the following code, I expected 4 users were displayed, then faded out, and the next four users would be displayed. Instead, it displayed all users, then faded out. What was wrong?

$(document).ready(function() {
  $.getJSON("MyjSON.json", function(data) {
    var text = '';
    var len = data.length;
    for (var i = 0; i < len; i++) {
      userName = data[i];
      text += '<p>' + i + '===========' + userName.user.name + '----> </p>'
      if ((i % 4) === 0) {
        console.log(i);
        $('#tFeed').append(text);
        $('#tFeed').fadeOut(3000).remove();
        // I tried $('#tFeed').fadeOut(3000); and it still did not work
        text = '';
      }
    }
  });
});

Animations and fading are asynchronous, but the rest of the loop runs synchronously and doesn't wait for it to complete.

You need to use the callback function of fadeOut() to defer actions until it completes.

You need to show the DIV again after it has faded out. And you should use .html() rather than .append() so the previous users are removed.

 const data = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]; function displayNext(arr, start, count) { let len = Math.min(arr.length, start + count); let text = ''; for (var i = start; i < len; i++) { const userName = arr[i]; text += '<p>' + i + '===========' + userName + '----> </p>' } $('#tFeed').html(text).show(); if (len == arr.length) { // last group $("#tFeed").fadeOut(3000); } else { $("#tFeed").fadeOut(3000, function() { displayNext(arr, start + count, count); }); } } displayNext(data, 0, 4);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="tFeed"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM