jQuery动画问题

I have a problem with an animation in jQuery using ajax.

On the click of an button (actually an tag), I call a ajax method, and have the following written inside the success parameter:

success: function(msg) {
  $('.ContentsMainRight').children().fadeOut(500, function() {
    $('.ContentsMainRight').html(msg.d);
    $('.ContentsMainRight').children().fadeIn(1000);
  });
},

This have the following result.

The contents of a div fade out over 500ms as it's supposed to. Then the html contents of the div are swapped, but then the last part did not work as I hoped. The html returned by the ajax method include some text inside a

tag, and a image inside a tag. The result is that the text is automatically displayed instantly with no fadein, but the img that is put fades in over 1 second. Why is the text and image treated differently?

-Daemon

Try:

success: function(msg) {
  $('.ContentsMainRight').fadeOut(500, function() {
    $('.ContentsMainRight').html(msg.d);
    $('.ContentsMainRight').fadeIn(1000);
  });
},

Basically the problem is that you hide the children and then replace the children with your html() call. The replaced content isn't hidden so it's instantly visible, which is what you're seeing.

Another issue is that if there are multiple children you will be replacing all the children on each child's callback. When you call fadeOut() on multiple elements, it's called separately for each element.

To give you an example of what I mean assume:

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

Compare:

$("ul").fadeOut(500, function() {
  alert("replacing");
  $(this).html("<li>four</li><li>five</li><li>six</li>").fadeIn(500);
});

with:

$("ul").children().fadeOut(500, function() {
  alert("replacing"); // this will be called three times
  $(this).html("<li>four</li><li>five</li><li>six</li>").children().fadeIn(500);
});

or to make it even more clear:

$("ul").children().fadeOut(500, function() {
  alert("replacing"); // this will be called three times
  $(this).append("<li>four</li><li>five</li><li>six</li>").children().fadeIn(500);
});

Most likely, .children() references elements, not text nodes. This means the styles that are applied to them won't persist when the text changes, meaning the text will not have display:none or visibility:hidden (whichever is applied).

Why don't you just fade out the .ContentsMainRight div?

success: function(msg) {
  $('.ContentsMainRight').fadeOut(500, function() {
    $('.ContentsMainRight').html(msg.d);
    $('.ContentsMainRight').fadeIn(1000);
  });
},