首页 > 解决方案 > 如何检查 div 中的段落数并使用 jQuery 删除其中一些?

问题描述

我是 jQuery 新手,我在 div 内使用套接字动态附加一些段落,所以我想知道段落数是否超过一定数量。如果段落的数量超过 10 个,我想保留最后 10 个并删除其他的。这就是我附加段落的方式:

socket.on("response", function (text) {
      $("div.paragraphs").append(
        '<p>' + text + '</p>'
      );
  });

这就是我正在尝试的:

$("div.paragraphs").change(function () {
    const matched = $("p");
    console.log("Number of paragraphs in div = " + matched.length);
  });

但是,控制台中没有显示任何内容。我想做这样的事情,但不知道我是否正确:

$("div.paragraphs").change(function () {
    const matched = $("p");
    if(matched.length){
      $('p:lt(matched.length-10)', 'div.paragraphs').remove()
    }
});

这是正确的方法吗?

标签: jquery

解决方案


也许这样的事情会介意我的代码注释:

socket.on("response", function (text) {
  $("div.paragraphs").append(
    '<p>' + text + '</p>'
  ); //now here... this means if you insert a new element and it is the 11nth, it will get erased... maybe you meant prepend?
  maintain_ten_elements(); //this is here since I assume you want the div never to be past 10.
});

 function maintain_ten_elements(){
    $("div.paragraphs p:nth(9)").nextAll().remove(); //sexy single line of code, takes the the 10nth element (9, because it starts from 0) and then takes all the elements after it (11 and on) and removes them.
}

推荐阅读