简体   繁体   English

JQuery 删除<li>使用 onclick 事件

[英]JQuery removing <li> using onclick event

I have a ul in which I'll add elements using JQuery, I have this我有一个 ul,我将在其中使用 JQuery 添加元素,我有这个

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.如果您使用的是onclick那么您必须使用引用调用该函数,因为this不会引用被单击的元素(最常见的是引用window对象)并基于该元素删除该元素。

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.或者,您可以使用现有函数,但在元素创建后使用 jQuery 绑定事件处理程序。

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

An another option would be event delegation which helps to handle events on dynamically created elements.另一种选择是事件委托,它有助于处理动态创建的元素上的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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