简体   繁体   中英

How to Append a element with a remove function with it

I'm trying to append a list element with a remove function with it. I already created the remove function and I can appended the element but have no idea how to append the element with the remove function with it.

here's the code

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#btn1").click(function () {
            var listname = $('#listname').val();
            $(".container").append($('<ol>', {
                text: listname
            }));
        });


        $("#btn2").on('click', function () {
            var name = $('#name').val();
            $('ol').append($('<li>', {
                text: name
            }));
        });

        $('ol').on('click', '.btn3', function () {
            $(this).parent('li').remove();

        });

    });
</script>
    <title></title>
</head>

<body>
    <ol>
        <li>List item 1 <button class="btn3">remove</button></li>
        <li>List item 2 <button class="btn3">remove</button></li>
        <li>List item 3 <button class="btn3">remove</button></li>
    </ol>
    <form>
        <input id="name" type="text"> <button id="btn2">Append list items</button> 
    </form>
</body>
</html>

Tips, comments will be much appreciated

Try

$("#btn2").on('click', function () {
    var name = $('#name').val();
    $('<li>', {
        text: name
    }).appendTo('ol').append($('<button />', {
        'class': 'btn3',
        text: 'Remove'
    }))
});

If the ol is added dynamically then

$(document).on('click', 'ol .btn3', function () {
    $(this).closest('li').remove();
});

Demo: Fiddle

create <li> append <button> to it.. and then append it to the <ol>

try this

 $("#btn2").on('click',function(){
 var name = $('#name').val();
 var $li=$('<li>', { text: name}); //creating li element.
   $li.append($('<button />',{text:"remove","class":"btn3"}).appendTo('ol');
   //--^^^^^^^^^---- append created button to lu            ---append  li to ol
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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