如何用jQuery检查div内的段落数并删除部分段落?

问题描述 投票:0回答:1

我是一个新的jQuery用户,我在一个div里面用socket动态添加一些段落,所以我想知道段落的数量是否超过了一定的数量,如果超过了,比如10个,我想保留最后的10个,并删除其他的段落。如果段落数超过了,比如说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
1个回答
0
投票

change 时,事件不会发生。元素 改变--只有当类似输入元素的元素发生变化时,它才会启动。价值观 的变化。虽然你可以用MutationObserver来观察变化,但是在你添加一个段落后(或者在所有段落被添加后,如果是分批添加的话)启动段落检查器会更优雅。

因为它看起来像一个新的 <p> 被附加在每个套接字消息上,你可以保持一个运行的总数量的 <p>到目前为止,已经追加了很多,一旦达到极限,就运行 $("div.paragraphs > p:first-child").remove() 去掉第一个 <p> 最老的一个)。

let pCount = 0;
socket.on("response", function(text) {
  $("div.paragraphs").append(
    '<p>' + text + '</p>'
  );
  pCount++;
  if (pCount > 10) {
    $("div.paragraphs").first().remove();
  }
});

现场演示(使用 setInterval 而不是套接字)。)

let pCount = 0;
setInterval(() => {
  $("div.paragraphs").append(
    '<p>' + Math.random() + '</p>'
  );
  pCount++;
  if (pCount > 10) {
    $("div.paragraphs > p:first-child").remove();
  }
}, 400);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="paragraphs">
</div>

0
投票

也许是这样的... ...注意我的代码注释

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.
}

0
投票

这里有一些你所描述的示例代码:

(我用一个手动添加段落的按钮代替了response.on, 只是为了验证概念. 你可以把删除第一个元素的代码移到你的回调函数中)。)

let counter = 0;

$("button").on("click", function() {

      $("div.paragraphs").append(
        '<p>Text' +  (counter++) + '</p>'
      );


    if ( $("div.paragraphs p").length > 10 ){
      $("div.paragraphs > p:first").remove()
    }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<div class="paragraphs"></div>

代码笔

© www.soinside.com 2019 - 2024. All rights reserved.