gpt4 book ai didi

javascript - 在 unorderdlist 中的指定 listItem 下插入项目,而不是在底部

转载 作者:行者123 更新时间:2023-11-30 14:50:19 25 4
gpt4 key购买 nike

我正在为一个网站制作一个评论系统,该系统通过 Ajax 请求获取评论并将它们添加到评论列表中。这工作正常,但它总是将它们添加到列表的底部。这是因为我正在使用 list.appendChild(item);为此,我现在需要找到替代方案...

有没有办法添加一个<li>另一个 <li> 下的元素我知道其中的 ID?

这是一个video包含当前行为

及其代码:

function loadcomments(id){
$.ajax({
url: '/ajax/getcomments/',
data: {
'identifier': '{{ identifier }}',
'id': id,
'begin': '0',
'end': '30',
},
dataType: 'json',
success: function (data) {
var json = JSON.parse(data.comments);
console.log(json);
makeUL(json);
function makeUL(array) {
list = document.getElementById('commentlist');
for(var i = 0; i < array.length; i++) {
if(!document.getElementById("comment-id-" + array[i].pk)){
var item = document.createElement('li');
item.className = "commentlistelement"
item.setAttribute('id',"comment-listitem-id-" + array[i].pk)
var maindiv = document.createElement('div')
maindiv.setAttribute('id',"comment-id-" + array[i].pk);
maindiv.className = "row comment";
maindiv.setAttribute("style","padding-left: "+3*array[i].fields.indent+"vw;");
maindiv.innerHTML = "<div class=\"col-md-1\">profile<br>pic</div><div class=\"col-md-9\"><small>"+ array[i].fields.user +" </small><small><button class=\"buttonlink\" onclick=\"reply("+ array[i].pk +")\">reply</button></small> <small><button class=\"buttonlink\" onclick=\"loadcomments("+ array[i].pk +")\">show more</button></small><br><p>" + array[i].fields.description + "</p></div>";
item.appendChild(maindiv);
list.appendChild(item);
}
}
return list;
}
}
});
};

最佳答案

您或许可以使用 Node 对象的 firstChildinsertBefore 方法:

https://developer.mozilla.org/en-US/docs/Web/API/Node/firstChild

https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore

JQuery 也有一个 insert after 方法:

http://api.jquery.com/insertafter/

获取列表容器的第一个 child 。然后在它前面插入。

关于javascript - 在 unorderdlist 中的指定 listItem 下插入项目,而不是在底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48242972/

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