【问题标题】:JQuery Add Button once to List ItemsJQuery将按钮一次添加到列表项
【发布时间】: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


【解决方案1】:

您可以使用$('li:last') 添加最后一个li,然后检查按钮的长度是否为0li 内,然后只添加删除按钮。

演示代码

let list = $('#list');
let input = $('#input');

function addDeleteButton() {
  let li = $('#list li:last'); //get last li added
  let button = '<button>delete</button>';
  //then check if the li doesnot has button in it
  if (li.find("button").length == 0) {
    li.append(button); //add that inside button
  }
  //or directly append button i.e : li.append(button); 
}

function addListItem() {
  let li = '<li>' + input.val() + '</li>';
  list.append(li);
  addDeleteButton();
}

$('#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>

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多