简体   繁体   中英

Click Event UI button jQuery

I am building a simple shopping list. Currently my code will delete an added list item when you click anywhere on the list item itself, I would like it to work where clicking on the UI button next to it will delete the entire item from the list, what I have tried will only delete the UI button itself. Thanks for the help, I am very much a novice

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

});

You can make 2 changes like

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

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM