gpt4 book ai didi

javascript - 我如何将 li 移动到 ul 的底部?

转载 作者:行者123 更新时间:2023-12-04 09:06:04 24 4
gpt4 key购买 nike

我试图将 li 移到 ul 的底部,但不知道该怎么做。我看过 Move the first four list items to the end of the listMove items in Ul Li up and down (这个不起作用,因为它是 JQuery 而我正在尝试使用 JS),但两者都不起作用。我什至尝试删除 li 并在之后重新添加它,但无法让 onclick 工作。
这是 ul:

<ul class="role_box_roles" id="rbroles">
<li class="role_box_role" style="border-color: rgb(255, 0, 0);">
<button class="role_remove_button" type="button" style="background-color: rgb(255, 0, 0);">-</button>
<span>Staff</span>
</li>
<li id="plusbutton"><button class="role_add" type="button" onclick="show_options()">+</button></li>
</ul>
我需要保留在底部的 li 是带有“plusbutton”ID 的那个。 (我说保持原位,因为每当我向 ul 添加新项目时,它都会添加到“plusbutton”li 下方)
add_option 函数:
function add_option(optionname) {
var listItem = document.createElement("li");
var removeButton = document.createElement("button");
var optionSpan = document.createElement("span");

listItem.className = "role_box_role";
listItem.style = "border-color: rgb(255, 0, 0);";

//removeButton.type = "button";
removeButton.innerText = "-";
removeButton.className = "role_remove_button";
removeButton.style = "background-color: rgb(255, 0, 0);";

optionSpan.innerText = optionname;

listUl = document.getElementById("rbroles");
listUl.appendChild(listItem);
listItem.appendChild(removeButton);
listItem.appendChild(optionSpan);
}

最佳答案

您可以简单地使用 before()也可以通过 referencing 做到这一点node (li) 要在它之前添加。
现场演示:

function add_option(optionname) {
var listItem = document.createElement("li");
var removeButton = document.createElement("button");
var optionSpan = document.createElement("span");

listItem.className = "role_box_role";
listItem.style = "border-color: rgb(255, 0, 0);";

//removeButton.type = "button";
removeButton.innerText = "-";
removeButton.className = "role_remove_button";
removeButton.style = "background-color: rgb(255, 0, 0);";

optionSpan.innerText = optionname;
listItem.appendChild(removeButton);
listItem.appendChild(optionSpan);

// Get reference node
var referenceNode = document.querySelector('#plusbutton');

// Add the new node before the reference node
referenceNode.before(listItem);
}
<ul class="role_box_roles" id="rbroles">
<li class="role_box_role" style="border-color: rgb(255, 0, 0);">
<button class="role_remove_button" type="button" style="background-color: rgb(255, 0, 0);">-</button>
<span>Staff</span>
</li>
<li id="plusbutton"><button class="role_add" type="button" onclick="show_options()">+</button></li>
</ul>


<button onclick="add_option('Blah')">
Add
</button>

关于javascript - 我如何将 li 移动到 ul 的底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63443887/

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