【问题标题】:jQuery .remove() and last-child not working as expectedjQuery .remove() 和 last-child 没有按预期工作
【发布时间】:2013-11-21 21:10:54
【问题描述】:

我有这个工作正常的代码。新的数据可以正常输入,但是当 p 的数量达到 3 时,什么也没有发生。最后一项不会被删除,也不会添加新项。

有什么想法吗?

setInterval(function() {
              $.post(
                'json.php', 
                function(data){
                    $('#tweetBox').append('<p>' + data + '</p>');
                    var list = $('#tweetBox p').length;
                    if (list > 3){
                        $('#tweetBox p:last-child').remove();
                    }               
                }
            );
        }, 5000);

【问题讨论】:

    标签: jquery css-selectors


    【解决方案1】:

    最后一项不会被删除,也不会添加新项。

    这表示新项目被附加但立即被删除。你想颠倒顺序:

    var list = $('#tweetBox p').length;
    if (list === 3){
        $('#tweetBox p:last-child').remove();
    }
    $('#tweetBox').append('<p>' + data + '</p>');
    

    【讨论】:

      【解决方案2】:
      $('#tweetBox p:gt(3)').remove();
      

      【讨论】:

        猜你喜欢
        • 2013-09-30
        • 1970-01-01
        • 2012-11-17
        • 2013-01-12
        • 2011-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        相关资源
        最近更新 更多