1

我正在尝试使用带有删除功能的列表元素附加它。我已经创建了 remove 函数,我可以附加元素,但不知道如何使用 remove 函数附加元素。

这是代码

<!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>

提示,评论将不胜感激

4

2 回答 2

1

尝试

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

如果ol是动态添加的,那么

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

演示:小提琴

于 2013-09-24T02:35:41.117 回答
0

创建<li>附加<button>到它..然后将它附加到<ol>

尝试这个

 $("#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
});
于 2013-09-24T02:37:28.983 回答