jQuery AJAX使用fadeIn和replaceWith方法

3

在SO上有几个关于这个问题的问答,但我没有找到解决我的问题的答案。我对此感到困惑。如果您知道可用的答案,请将我重定向到链接。

我的页面有一个空的DIV #posts_insert,通过Ajax插入新的帖子。

    $.ajax({
        url: 'chat/posts_submit/' + <?php echo $page_id; ?>,
        type: 'POST',
        data: $('#posts_form').serialize(),
        dataType: 'html',
        success: function(html) {
            $('#posts_insert').replaceWith(html);
        }
    });

我希望新文章能够淡入,替换掉#posts_insert。我已经尝试了几种用hide()fadeIn之前的success迭代,但是我就是无法让它工作。

有什么想法可以解决这个问题吗?谢谢提前。


你尝试过这个吗?$('#posts_insert').replaceWith(html).fadeIn('slow') - kobe
3个回答

11

谢谢@andrew,你的代码非常好。但是我不知道为什么我又遇到了一个错误,就像@eric一样。完整的消息是uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMViewCSS.getComputedStyle]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no] - pepe
@torr:我会检查是否有缺少的标签等问题。或许可以通过验证器运行从服务器返回的HTML代码。 - Andrew Whitaker
该解决方案不会使原始内容褪色。 - Eric
@Andrew:原始措辞含糊不清。我只是想向OP指出区别。 - Eric
旧内容不需要消失--每篇文章都在单独的div中,新文章插入到旧文章之上,在#posts_insert内部,因此旧文章被向下推动--我想要的只是新文章淡入而不是突然出现。 - pepe
显示剩余3条评论

0

像这样吗?

$.ajax({
    url: 'chat/posts_submit/' + <?php echo $page_id; ?>,
    type: 'POST',
    data: $('#posts_form').serialize(),
    dataType: 'html',
    success: function(html) {
        var newContent = $(html);
        $('#posts_insert').fadeOut(function() {
            $(this).replaceWith(newContent.hide());
            newContent.fadeIn();
        });
    }
});

谢谢 @eric - 这个代码返回了一个不断循环的“未捕获异常”错误。 - pepe

-1

你可以尝试:

success: function(html) {
   var $container = $('#posts_insert').parent();
   $container.fadeOut('fast', function() {
      $('#posts_insert').replaceWith(html);
      $container.fadeIn();
   });
}

可能会给你想要的效果。

编辑: 为什么不在(#posts_insert)周围放一个容器,将其淡出,用replaceWith()替换,然后淡入容器呢?


2
replaceWith 返回原始元素。因此,它将淡入 #posts_insert 元素,而不是刚检索到的 HTML。 - Eric
不幸的是,它不起作用——最终结果与我的原始代码相同-感谢建议。 - pepe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接