简体   繁体   English

从ul中删除和编辑动态创建的li

[英]Delete and edit a dynamically created li from ul

I am creating li by giving input from inputbox and appending the data in li by using jquery but after adding the li I have added a delete button, but it works, but deleting all li by clicking any delete button. 我通过从输入框提供输入来创建li ,并使用jquery在li追加数据,但是在添加li之后,我添加了删除按钮,但是它可以工作,但是可以通过单击任何删除按钮来删除所有li How can I delete one by one. 如何一一删除。 And one more thing how can I edit those li by clicking? 还有另一件事,我该如何通过单击来编辑那些li

This is the code: 这是代码:

$('#submit').on('click', function(){
    var $item = $('#addList').val();

    if($item.trim() == ''){
        alert('please enter the value');
    } else {
        $('ul#listItem').append('<li>'+ $item + '<button class="btn">delect</button>' + '</li>');

        $(document).on('click', '.btn', function(){
            $('ul#listItem > li').remove();
            return false;
        });
    }

    $item = $('#addList').val(' ');
});

This is the html: 这是html:

<form>
    <input type="text" id="addList">
    <input type="button" id="submit" value="Add">
</form>

try this 尝试这个

$(document).on('click', 'ul#listItem > li .btn', function(){
    $(this).closest('li').remove();
    return false;
});

Use this JavaScript to capture all at once: 使用此JavaScript一次捕获所有内容:

$(document).on('click', 'ul#listItem li button.btn', function() {
    $(this).closest('li').remove();
});

When clicking anywhere in your document (complete window), it checks wether the target matches the selector ul#listItem li button.btn , which are the buttons in your list. 单击文档中的任何位置(完整窗口)时,它将检查目标是否与选择器ul#listItem li button.btn匹配,这些选择器是列表中的按钮。 It then looks for the closest li , which is the one around the button, and removes it, including the button itself. 然后,它寻找最接近的li ,它是按钮周围的那个li ,并删除它,包括按钮本身。

Your whole code becomes as following 您的整个代码如下

$('#submit').on('click', function(){
    var $item = $('#addList').val();

    if($item.trim() == '') {
        alert('please enter the value');
    } else {
        $('ul#listItem').append('<li>'+ $item + '<button class="btn">delect</button>' + '</li>');

    }
    $item = $('#addList').val(' ');
});

$(document).on('click', 'ul#listItem li button.btn', function() {
    $(this).closest('li').remove();
});

Change 更改

$(document).on('click', '.btn', function(){
     $('ul#listItem > li').remove();
     return false;
});

To: 至:

$(document).on('click', '.btn', function(){
    $(this).parent("li").remove();
    return false;
});

Should work :) 应该管用 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM