伙计们,我将感谢您对此的善意指导。我正在我的网站上建立一个论坛页面,其中包含帖子/评论功能。
这是我的jquery文件的获取帖子部分:
function fetchPosts(){
var url = "fetch_posts.php";
$.getJSON(url, function(data){
$.each(data, function(i, user){
if ($("#comment_thread").children("p[data-id='"+user.id+"']").exists()){
var postHtml = '<div class="col-md-1"><img src="images/user.png" alt="image" width="50px" height="50px" background="#FC6806"></div><div class="col-md-11"><h5 style="color:#FC6806"><strong>'+user.name+'</strong></h5><h6 style="color:#FC6806">'+user.time+'</h6><h5 style="color:#0269C2"><strong>'+user.topic+'</strong></h5><p data- id="'+user.id+'">'+user.post+'</p></div><br/>';
$("#comment_thread").append(postHtml);
}
});
});
}
fetchPosts();
setInterval(fetchPost, 5000);
现在我写了一个 setInterval 函数,每 5 秒刷新一次页面。
这样做的效果是,每次这样做时,它都会再次附加从数据库中获取的所有帖子,并且这种情况一直持续下去。
我想合并的是,每次页面刷新时,都应该检查获取的帖子的帖子 ID,并且页面上的任何一个已经不应该附加,而应该附加新的帖子。
我尝试选择孩子,然后检查是否有任何人具有当前页面上帖子 ID 的数据 id 属性,但我收到错误:
"Uncaught TypeError: $(...).children(...).exists is not a function"
感谢您的帮助。
使用 length
查看 jQuery 选择器是否返回匹配项
if ($("#comment_thread").children("p[data-id='"+user.id+"']").length){
那是因为$("#comment_thread").children("p[data-id='"+user.id+"']")
返回 null。您应该使用if ($("#comment_thread").children("p[data-id='"+user.id+"']").length > 0) {
来检查它是否在页面上。