我正在尝试创建一个动态项目列表,可以添加到动画中或从动画中删除。我遇到的问题是新项目无法删除。关于我做错了什么的任何想法?
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;
});
答案 0 :(得分: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;
});
答案 1 :(得分:0)
更改要删除的js功能
$('#list').on('click', '.remove-item', function(){
$(this).parent().animate({opacity: 0}, function () {
$(this).slideUp();
});
});