gpt4 book ai didi

javascript - 判断元素是否存在

转载 作者:行者123 更新时间:2023-11-30 08:13:32 25 4
gpt4 key购买 nike

正在为 Web 应用程序创建评论系统,当用户单击评论图像时加载评论,使用 json 动态生成 html 代码以显示评论。但是当再次点击图片时,再次请求用相同的数据填充页面

这是我的代码

function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$.getJSON(action,function(data) {
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p><a href="">'+item.user_id+'</a></p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span>'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'</div>'+
'</div>'
);
});
});
}



function retrieve_comments(pheed_id) {
var action = url+'comments/get_comments';
var crsf = $('input[name=ci_csrf_token]').val();
var dataString = "pheed_id="+pheed_id+"&ci_csrf_token="+crsf;
$.ajax({
url:action,
type:'POST',
cache:false,
dataType:'json',
data:dataString,
success:function(data) {
$.each(data,function(index,item) {
$("#" + pheed_id).append(
'<div class="pheed_comments">'+
'<div class="comment">'
+'<span><p>'+item.user+'</p></span>'
+item.comment+
'</div>'+
'</div>'+
'<div id="comment_box">'+
'<textarea id="comment" cols="30">'+
'</textarea><br>'+
'<input type="button" class="submit_btn" value="comment" />'+
'</div>'
);
});
}
});
}

latest_pheeds() 加载 pheeds,retrieve_comments 获取传递给它的 pheed_id 的评论。我如何确定评论区域是否已被填充,并在可用时用新评论更新它。谢谢

最佳答案

检查

$("#" + pheed_id +' .pheed_comments').length

如果元素(我猜你的意思是 div.pheed_comments )不存在,if 将为 0。

关于javascript - 判断元素是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7169377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com