gpt4 book ai didi

javascript - To do list in Javascript - 如何始终将新元素插入列表顶部?

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:21 25 4
gpt4 key购买 nike

我有一个待办事项列表,看起来类似于:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_todo

用户应该输入一个任务,以便将其添加到列表中。与我链接到的那个不同,我希望最新的输入始终位于列表的顶部,而不是添加到底部。我试过使用 insertbefore() 函数,但我不知道如何让它工作

这是我的代码:

tasks = [];

function addTask() {

var li = document.createElement("li");

// Adding checkbox
var cbox = document.createElement('INPUT');
cbox.setAttribute('type', 'checkbox');
li.appendChild(cbox);
cbox.setAttribute('id', 'box');

// Adding thing to do
var inputValue = document.getElementById("newTask").value;
var task = document.createTextNode(inputValue);
li.appendChild(task);

if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("list").appendChild(li);
}

// Part 3
tasks.push(newTask.value);

document.getElementById("newTask").value = '';
}



// Prevent Default
document.getElementById("submit").addEventListener("click", function() {
event.preventDefault()
});
body {
width: 600px;
margin: auto;
background: #ffe699;
font-family: garamond;
font-size: 20px;
}

ul {
list-style-type: none;
padding: 0;
border: 2px solid black;
}

ul li {
padding-top: 15px;
padding-bottom: 15px;
font-weight: bold;
}

fieldset {
background: skyblue;
border: 2px solid black;
}

ul li:nth-child(odd) {
background-color: skyblue;
}

ul li:nth-child(even) {
background-color: white;
}

ul li:hover {
background-color: aqua;
}

#box {
margin: 0px 20px 0px;
}
<h1> To do list </h1>

<form class="" action="todo.html" method="post">
<fieldset>
<label> Add a task in the input field below </label> <br><br>
<input id="newTask" type="text" placeholder="Type a task here" autofocus> <br><br>
<input id="submit" onclick="addTask()" type="submit" value="Add task"><br><br>
<output name="result"> Hallo </output>
</fieldset>
</form>

<h2>List of things to do</h2>

<ul id="list">
</ul>

最佳答案

而不是像这样 appening child

document.getElementById("list").appendChild(li);

只需将它插入到第一个 child 之前

像这样:

var list = document.getElementById("myList");
list.insertBefore(newItem, list.childNodes[0]);

这里有一个非常清楚的例子:

Example link

关于javascript - To do list in Javascript - 如何始终将新元素插入列表顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52986512/

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