Javascript jQuery元素删除

Javascript jQuery元素删除,javascript,jquery,html,Javascript,Jquery,Html,我想使用jQuery删除一个元素 HTML: 这不管用。但另一方面,如果我尝试整体删除列表项,则代码可以工作: $("#listContainer").on("click", ".deleteBtn", function() { $(this).closest(".listItem").remove(); }); 为什么会这样 谢谢。因为。最近的会传播到HTML的顶部。因此,它会搜索与选择器匹配的第一个父级。这就是它找不到的原因。ammonInput。因为它不是按钮的父级 要获得.am

我想使用jQuery删除一个元素

HTML:

这不管用。但另一方面,如果我尝试整体删除
列表项
,则代码可以工作:

$("#listContainer").on("click", ".deleteBtn", function() {
    $(this).closest(".listItem").remove();
});
为什么会这样


谢谢。

因为
。最近的
会传播到HTML的顶部。因此,它会搜索与选择器匹配的第一个父级。这就是它找不到的原因。
ammonInput
。因为它不是按钮的父级

要获得
.ammonInput
,您必须:

$(“#listContainer”)。在(“单击”,“删除BTN”,函数()上{
$(this).closest(“.listItem”).find(“.ammonInput”).remove();

});因为
.closest
会传播到HTML的顶部。因此,它会搜索与选择器匹配的第一个父级。这就是它找不到的原因。
ammonInput
。因为它不是按钮的父级

要获得
.ammonInput
,您必须:

$(“#listContainer”)。在(“单击”,“删除BTN”,函数()上{
$(this).closest(“.listItem”).find(“.ammonInput”).remove();

});您的选择器不正确,在这种情况下,使用“查找”而不是“最近”可能会有所帮助,而且示例中的$(此)与deleteBtn类相关,而不是与listContainer相关

$(“#listContainer”)。在(“单击”,“删除BTN”,函数()上{
console.log($(this))//这是.deleteBtn而不是listContainer
$(this).closest(“.listItem”).find(“.amountInput”).remove();
});

项目名称
X

您的选择器不正确,在这种情况下,使用“查找”而不是“最近”可能会有所帮助,而且示例中的$(此)与deleteBtn类相关,而不是与listContainer相关

$(“#listContainer”)。在(“单击”,“删除BTN”,函数()上{
console.log($(this))//这是.deleteBtn而不是listContainer
$(this).closest(“.listItem”).find(“.amountInput”).remove();
});

项目名称
X

改用this
$(this).closest(.listItem”).find(.amountInput”).remove()
转到父级,然后查找不起作用的
amountInput
,因为
.closest(…)
查找祖先,而您正在尝试查找兄弟。请改用此
$(this).closest(.listItem”).find(.amountInput”).remove()转到父级,然后查找不起作用的
amountInput
,因为
。最近的(…)
查找祖先,而您正在尝试查找兄弟。这将删除所有
。amountInput
这将删除所有
。amountInput
$("#listContainer").on("click", ".deleteBtn", function() {
    $(this).closest(".amountInput").remove();
});
$("#listContainer").on("click", ".deleteBtn", function() {
    $(this).closest(".listItem").remove();
});