【问题标题】:how to use jquery.before() to insert before Dom elements?如何使用 jquery.before() 在 Dom 元素之前插入?
【发布时间】:2014-01-25 13:33:42
【问题描述】:

我正在使用此代码在特定 div 中的所有元素之前插入。

 $.post('getcomments.php', {rid:1, frm: 10,to:20}, function(data) {
                            $("#main_post_comments").before(data);
                    });

页面第一次加载功能正常 但之后总是附加在原始 html 代码中编写的原始 html 元素之前,而不是我使用 $.post 请求的最后一个附加元素

这是页面第一次加载(第一项是评论 102):

这是在正确插入第一条评论(评论 103 插入到 102 之后)之后:

这是在插入第二条评论之后(评论 104 也插入在评论 102 之后)

如何在“#main_post_cmets”中的每个元素之前插入新数据,即使它是动态插入的?

【问题讨论】:

  • 听起来你可能想要.prepend() 而不是.before()

标签: javascript php jquery html


【解决方案1】:

使用前置而不是之前

  $("#main_post_comments").prepend(data);

【讨论】:

    【解决方案2】:

    试试这个:

    $.post('getcomments.php', {rid:1, frm: 10,to:20}, function(data) {
                                $("#main_post_comments").insertBefore(data);
                        });
    

    也许你正在寻找 insertBefore();

    http://api.jquery.com/insertbefore/

    【讨论】:

    • .insertBefore().before() 做同样的事情,但语法相反。您显示的代码将尝试插入 #main_post_comments before datadata 尚未在 DOM 中。
    • 最近附加部分的 id 是什么?你必须将它附加到最后一部分,如果 id 总是“main_post_cmets”,那么它会一直寻找它。所以也许添加一个计数器 var i 并将 id 更改为 "#main_post_cmets_"+i;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多