jquery - 如何检查 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()
}
});
这是正确的方法吗?
解决方案
也许这样的事情会介意我的代码注释:
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.
}
推荐阅读
- java - 如何在 gradle 中使用 init 脚本配置 jacocoTestReport
- django - 如果填写了一份表格,则 Django 中不需要其他表格
- dask - adlfs:使用 credential=None 创建 AzureBlobFileSystem?
- python - 结合GridSearch自定义交叉验证功能
- javascript - 我们如何在 read-more-react - npm 中使用 dangerouslySetInnerHTML?
- c# - 重新创建 XML 但将变量传递到数据中
- api - 如何使用带有 lambda 的 CORS 进行重定向
- r - 如何将 JSON 转换为 DF?
- r - R错误:UseMethod(“weekdays”)中的错误:没有适用于“工作日”的适用方法应用于“字符”类的对象
- python - 有没有一种方法可以在每次迭代时将新列表附加到现有列表中?