gpt4 book ai didi

javascript - 无法使用 $.each() 迭代器函数从数组中获取当前值

转载 作者:行者123 更新时间:2023-11-28 04:44:11 25 4
gpt4 key购买 nike

我正在尝试使用 Jquery 创建一个简单的待办事项应用程序。但是,当我点击添加按钮时尝试显示当前值似乎会产生异常,即单击添加按钮时会显示所有数组项。我在下面包含了我的代码片段。我按照我在此处看到的步骤进行操作 http://api.jquery.com/jquery.each/

var inputVal = $('#formField').val()
var todoList = $('#todolist');


var todos = [];
function createTodo(item){
// Return a todo object
}

function removeTodo(index){
// Remove todo from todos at index
}

function addTodo(todo){
//Add todo to todos

todos.unshift($('#formField').val())
}

function renderTodos(){
$.each(todos, function( index, value ) {
$('.todolist').prepend(`<li> ${value}<span class delete> X </span> </li>`);
});
}

$('#subBut').click(function (e) {

addTodo(inputVal);
renderTodos()

});
.center {
margin: auto;
width: 50%;
text-align: center;
padding: 10px;
}

ol {
width: 70%;
margin: auto;
padding: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToDo App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<div class="center">
<h2>My Todo App</h2>
<div id="taskForm">
<input type="text" placeholder="Enter a task" id="formField">
<input type="button" id="subBut" value="Add">
</div>

</div>

<div id="result">
<ol class="todolist">

</ol>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="/script/script.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</body>
</html>

最佳答案

.todolist 已经包含了一些项目,而您正试图再次将所有项目添加到前面,这就是您得到重复项的原因。您可以在再次添加之前使用 .empty() 清除 .todolist

关于javascript - 无法使用 $.each() 迭代器函数从数组中获取当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633781/

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