jQuery自关闭已在运行时创建的li

时间:2019-02-12 22:06:18

标签: javascript jquery

我有一些jquery代码在运行时添加列表项:

function addlistitem() {

$('#mylist ul').append(`
   <li class="list-group-item">
    <button onclick="selfclose()">Del</button>
       Some Text Here
  </li>`); 

}

html是:

<div id='mylist'>
  <ul class="list-group"></ul>
</div>

单击按钮时如何自动关闭添加的列表项?

2 个答案:

答案 0 :(得分:1)

this传递到selfclose。然后使用它找到封闭的li并将其删除。

function addlistitem() {

  $('#mylist ul').append(`
   <li class="list-group-item">
    <button onclick="selfclose(this)">Del</button>
       Some Text Here
  </li>`);

}

$("#add").click(addlistitem);

function selfclose(el) {
  $(el).closest("li").remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='mylist'>
  <ul class="list-group"></ul>
</div>
<button id="add">Add LI</button>

答案 1 :(得分:1)

如果不使用我一直不鼓励的内联onclick="",则jQuery可以重写为:

const $myList = $('#mylist ul'); // Cache your reusable static elements

const addListItem = (cont) => $('<li/>', {
  appendTo: $myList,
  'class': 'list-group-item',
  html: typeof cont === 'string' ? cont : 'Some <b>HTML</b> content Here',
  prepend: $('<button/>', {
    text: '\u2715',
    title: 'Remove list item',
    click() {
      $(this).closest('li').remove()
    }
  })
});

$("#add").on('click', addListItem);

// Additional example: Create some LI on app init:
addListItem("I'm created <b>on init</b>");
addListItem(":) me too!");
<button id="add">INSERT NEW</button>
<div id='mylist'><ul class="list-group"></ul></div>

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>