【问题标题】:how to make a list of items that can be added to or removed using jquery?如何制作可以使用 jquery 添加或删除的项目列表?
【发布时间】:2014-04-13 23:55:13
【问题描述】:

我正在尝试创建一个可以通过动画添加和删除的动态项目列表。我遇到的问题是新项目无法删除。关于我做错了什么有什么想法吗?

http://jsfiddle.net/waspinator/nZ9y2/1/

html

<button class="add-item-button"> add item </button>
<div id="list">
    <!-- prepend new item here -->
    <div class="item">
        First Item
        <span class="remove-item">x</span>
    </div>
    <div class="item">
        Second Item
        <span class="remove-item">x</span>
    </div>  
</div>

css:

#list{
    width: 140px;
}

.remove-item{
    font-family: sans-serif;
    float: right;
    margin-top: -6px;
    cursor: pointer;
}

.item{
    color: white;
    background: CornflowerBlue;
    margin-bottom: 4px;
    padding: 4px;
    border-radius: 4px;
}

.add-item-button{
    margin-bottom: 10px;
    width: 140px;
}

js

var item_number = 1;

$('.remove-item').click(function(){  
    $(this).parent().animate({opacity: 0}, function () {
        $(this).slideUp();
    });
});


$('.add-item-button').click(function() {
    var new_item = '<div class="item">' +
        'New Item ' + item_number +
        '<span class="remove-item">x</span>' +
        '</div>'

    $(new_item).prependTo('#list').hide().slideDown();
    item_number = item_number + 1;
});

【问题讨论】:

    标签: jquery


    【解决方案1】:

    绑定到#list,因为它始终在dom中,然后选择.remove-item类。这是小提琴:http://jsfiddle.net/nZ9y2/3/

    var item_number = 1;
    
    var remove = function() {  
        $(this).parent().animate({opacity: 0}, function () {
            $(this).slideUp();
        });
    }
    
    $('#list').on('click', '.remove-item', remove);
    
    $('.add-item-button').click(function() {
        var new_item = '<div class="item">' +
            'New Item ' + item_number +
            '<span class="remove-item">x</span>' +
            '</div>' 
        $(new_item).prependTo('#list').hide().slideDown();
        item_number = item_number + 1;
    });
    

    【讨论】:

      【解决方案2】:

      将移除的js函数改为

      $('#list').on('click', '.remove-item', function(){  
          $(this).parent().animate({opacity: 0}, function () {
              $(this).slideUp();
          });
      });
      

      http://jsfiddle.net/waspinator/nZ9y2/4/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        • 2020-01-06
        • 2014-05-05
        • 1970-01-01
        • 1970-01-01
        • 2017-01-17
        • 1970-01-01
        相关资源
        最近更新 更多