我是jQuery的新手,所以希望这不是两个愚蠢的问题,但我已经环顾四周了。
我有一个显示here的简单待办事项清单:我很好奇为什么当我点击显示的图像时(添加项目后),这些功能什么都不做。
以下两种关注方法......我很确定它们没有被调用。我不确定为什么:
$('.delete').on('click', function(event) {
event.preventDefault();
var reply = confirm("Are you sure you want to delete this todo item?");
if(reply === true) {
$(this).closest('.item').remove();
}
});
$('.edit').on('click', function(event) {
$(this).closest('.item').slideDown('fast');
});
答案 0 :(得分:6)
您可以按如下方式使用事件委托:
$('#list').on('click', '.delete', function(event) {
event.preventDefault();
var reply = confirm("Are you sure you want to delete this todo item?");
if(reply === true) {
$(this).closest('.item').remove();
}
});
$('#list').on('click', '.edit', function(event) {
$(this).closest('.item').slideDown('fast');
});
另一种更有效的选择是定义点击处理程序,然后在创建后将它们分配给元素:
var onDeleteButtonClicked = function(event) {
//delete code from above.
};
var onEditButtonClicked = function(event) {
//edit code from above.
};
function addTo(event) {
event.preventDefault();
var toAdd = $('#addition').val();
if(toAdd.length > 0) {
var listItem = $('<li class="item">' + toAdd + '</li>');
var img = $('<img class="delete" src="https://cdn1.iconfinder.com/data/icons/uidesignicons/delete.png">')
.click(onDeleteButtonClicked); //Assign your delete click handler here.
var img1 = $('<img width="4%" class="edit" src="https://cdn1.iconfinder.com/data/icons/freeapplication/png/24x24/Modify.png">')
.click(onEditButtonClicked); //Assign your edit click handler here.
listItem.append(img);
listItem.append(img1);
$('#list').append(listItem);
$('#addition').val("")
} else {
alert("Cannot add empty list item!");
}
}
答案 1 :(得分:1)
试试这个:
$('#container').on('click','.delete' ,function(event){
event.preventDefault();
var reply = confirm("Are you sure you want to delete this todo item?");
if(reply === true) {
$(this).closest('.item').remove();
}
});