简体   繁体   中英

JQuery removing <li> using onclick event

I have a ul in which I'll add elements using JQuery, I have this

function addElement(e) {
    let text = $('#itemToAdd').val();
    let newItem = $('<li>' + text + '</li>');
    let removeBtn = $('<button onclick = "removeElement">X</button>');

    newItem.append(removeBtn);
    $('#shoppingList').append(newItem);
    $('#itemToAdd').val('');
    e.preventDefault();
}

$(document).ready(function() {
    $("#addBtn").on('click', addElement);
});

For removing the elements I have this:

function removeElement() {
    $(this).parent().remove();
}

The adding function works awesome, but the removing one doesn't.

If you are using onclick then you have to invoke the function with the reference since this won't refer to clicked element(refers to window object most commonly) and based on that remove that element.

Element creation:

let removeBtn = $('<button onclick = "removeElement(this)">X</button>');

Function :

function removeElement(ele) {
    $(ele).parent().remove();
}

Or alternately you can use the existing function but bind event handler using jQuery after element creation.

let removeBtn = $('<button>X</button>');
removeElement.click(removeElement);

An another option would be event delegation which helps to handle events on dynamically created elements.

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