Jquery:当单击模态确认按钮时,删除动态生成的元素



例如:

<body>
<div class="container">
<!-- Generated by ajax -->
<div class="item" id="item_1">
<span class="remove-item"></span>
</div>
<div class="item" id="item_2">
<span class="remove-item"></span>
</div>
</div>

<div class="modal" id="removeItemModal">
<h3>Are you sure you want to remove?</h3>
<input type="hidden" id= "removeItemIdModalInput">
<button type="button">Cancel</button>
<button type="button" id="remove-confirm-btn">Confirm</button>
</div>
</body>

当单击remove-item类时,当用户单击confirm,移除整个(父(项时,将显示带有两个按钮ConfirmCancel的模态。我怎样才能做到这一点??以下是我所做的:

$(document).on("click",".remove-item", function (e) {
var removeProductId = $(this).closest(".item").attr("id");
// Setting the value in modal's hidden input
$("#removeItemIdModalInput").val(removeProductId);
$("removeItemModal").modal('toggle');
});
$(document).on("click","#remove-confirm-btn", function (e) {
var removeProductId = $("#removeItemIdModalInput").val();
$("removeItemModal").modal('toggle');
// Removing the container div/item
$(removeProductId).fadeOut(300,function () { $(this).remove();});

});

但它不起作用。为什么?有更好的方法吗?

[EDIT]
TS想要一个模式窗口,这个答案提供了一个替代


您也可以使用confirm()来代替模式窗口。

如果已确认,则使用parent()选择跨度的父元素,淡出该元素,然后移除。就像你已经做过的一样。

还要注意,您同时使用remove-itemremove_item,我将其全部更改为remove_item

$(document).on("click", ".remove_item", function(e) {
if(confirm("Do you want to remove this box")) {
$(this).parent().fadeOut(300, function () { $(this).remove();});
}
return;
});
#item_1, #item_2 {
border: 1px solid black;
margin: 2em;
}
.remove_item {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<!-- Generated by ajax -->
<div id="item_1">
Item 1
<span class="remove_item">remove</span>
</div>
<div id="item_2">
Item 2
<span class="remove_item">remove</span>
</div>
</div>

以下是解决我的问题的方法:

$(document).on("click","#remove-confirm-btn", function (e) {
var removeProductId = $("#removeItemIdModalInput").val();
$("removeItemModal").modal('toggle');
// Changed here
$("body").find(removeProductId).fadeOut(300,function () { $(this).remove();});

});

最新更新