【发布时间】:2021-06-13 04:44:42
【问题描述】:
每当用户按下“添加项目”按钮时,我都会将项目添加到列表中。发生这种情况时,应使用 JQuery 添加列表项。此外还有另一个功能,它会为每个列表项添加一个删除按钮,以便可以删除列表项。
我的问题是每次按下“添加项目”按钮时都会触发 addDeleteButton 功能,从而添加大量删除按钮。我的 addDeleteButton 获取所有列表项的 JQuery 对象并遍历它们。循环将查找现有的删除按钮,如果当前没有删除按钮,则仅添加删除按钮。但是我似乎找不到写这个条件的正确方法。如何确保只有在没有上一个按钮的情况下才添加删除按钮?
//gets element with id list so items can be appended to it
let list = $('#list');
//adds a delete button to the li element (only one button added per li)
function addDeleteButton() {
let li = $('li');
let button = '<button>delete</button>';
//this condition should limit the number of buttons added to each li
if (li.children(button) < 1) {
li.append(button);
}
}
//function adds new item to list
function addListItem() {
let li = '<li>' + input.val() + '</li>';
list.append(li);
addDeleteButton();
}
//listens for a click of the "Add" button which triggers list item to be added to list
$('#addLiButton').on('click', addListItem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="list">
<input type="text" name="item" id="input" />
</form>
<div id="addLiButton">Add Item</div>
<ol id="list"></ol>
【问题讨论】:
-
我弄乱了你的代码。编辑它并添加所有相关代码以使minimal reproducible example 解决您的问题。
-
li.children()不返回数字,它返回一个 jQuery 对象。也不能在children()中使用完整的 html 字符串作为选择器
标签: jquery list loops iteration