2014-09-06 129 views
0

我正在構建一個簡單的購物清單。目前,我的代碼會刪除一個添加的列表項目,當你點擊列表項目本身的任何地方時,我希望它能夠工作,點擊旁邊的UI按鈕將從列表中刪除整個項目,我試過的東西只會刪除UI按鈕本身。感謝您的幫助,我非常新手單擊事件UI按鈕jQuery

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); 
    } 
}); 

});

回答

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

+0

太棒了!謝謝! – user3795958 2014-09-06 01:22:05