我正在建立一个简单的购物清单。当你点击列表项目本身的任何地方时,我的代码将删除一个添加的列表项目,我希望它能够工作,点击它旁边的UI按钮将从列表中删除整个项目,我尝试过的只会删除UI按钮本身。谢谢你的帮助,我是一个非常新手
HTML
<div id="list">
<ul class="shopping"></ul>
</div>
的jQuery
$(document).ready(function () {
function addItemToList(e) {
var addItem = $('#item').val();
$('.shopping').append('<li>' + '<button class="uibutton"></button>' + addItem + '</li>');
$('.uibutton').button({
icons: {
primary: "ui-icon-heart"
},
text: false
});
$('ul').on('click', 'li', function() {
$(this).remove();
});
$('#item').val('');
}
/*adds list item to list when cart icon is clicked, clears #item input field*/
$('#toadd').click(function (e) {
addItemToList(e);
});
/*adds list item to list when enter key is hit, clears #item input field*/
$('#item').keydown(function (e) {
if (e.which == 13) {
addItemToList(e);
}
});
});
答案 0 :(得分:1)
您可以进行2次更改,例如
$(document).ready(function () {
function addItemToList(e) {
var addItem = $('#item').val();
var $li = $('<li>' + '<button class="uibutton"></button>' + addItem + '</li>').appendTo('.shopping');
//target only newly added button
$li.find('.uibutton').button({
icons: {
primary: "ui-icon-heart"
},
text: false
});
$('#item').val('');
}
//use event delegation instead of adding the handler in another event handler...
$('ul.shopping').on('click', '.uibutton', function () {
$(this).closest('li').remove();
});
/*adds list item to list when cart icon is clicked, clears #item input field*/
$('#toadd').click(function (e) {
addItemToList(e);
});
/*adds list item to list when enter key is hit, clears #item input field*/
$('#item').keydown(function (e) {
if (e.which == 13) {
addItemToList(e);
}
});
});
演示:Fiddle