简体   繁体   English

热从 javascript 反转 html 列表的顺序?

[英]Hot to reverse the order of a html list from javascript?

I currently have this code in JavaScript我目前在 JavaScript 中有此代码

function addTask() {
    // Declaring Variables
    var item = document.getElementById("text_field").value;
    var text = document.createTextNode(item);
    var list_element = document.createElement("li");
    var checkbox = document.createElement("input");
    
    checkbox.setAttribute("type", "checkbox");
    list_element.appendChild(checkbox);
    list_element.appendChild(text);
    document.getElementById("todo-list").appendChild(list_element);
}

This works fine to create a list, but the list items are added at the bottom of the html list.这适用于创建列表,但列表项添加在 html 列表的底部。 How do I add the new user input to the top of the html list?如何将新用户输入添加到 html 列表的顶部?

I think you can place them in an array then reverse them.我认为你可以将它们放在一个数组中然后反转它们。 this will be an example below这将是下面的一个例子

    function addTask() {
        // Declaring Variables
        var item = document.getElementById("text_field").value;
        var text = document.createTextNode(item);
        var list_element = document.createElement("li");
        var checkbox = document.createElement("input");
    
    checkbox.setAttribute("type", "checkbox");
    list_element.appendChild(checkbox);
    list_element.appendChild(text);
    document.getElementById("todo-list").appendChild(list_element);
}
    function reverseElement(){
 var reversedElement = Array.from(document.getElementById("todo-list")).reverse()
} 

Use prepend instead of append .使用prepend而不是append

Here is the working example:这是工作示例:

 function addTask() { // Declaring Variables var item = document.getElementById("text_field").value; var list_element = document.getElementById('tasks'); var li = document.createElement("li"); li.innerText = item; list_element.prepend(li); }
 <input id="text_field" /> <button onclick="addTask()">Add</button> <div> <h1>Tasks</h1> <ol id="tasks"></ol> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM