javascript - Jquery: Removing dynamically generated element when modal confirmation button is clicked
问题描述
For example:
<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>
When clicked on the remove-item
class a modal will be shown with two button Confirm
and Cancel
when user clicks on confirm, remove the whole (parent) item. How can i achieve this??
Here's what i did:
$(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();});
});
But It's not working. Why? Is there a better approach?
解决方案
[EDIT]
TS wants a modal window, this answer provides an alternative
Instead of a modal window, you can use confirm()
too.
If that is confirmed, you select the parent of the span, by using parent()
, fade that element out, and remove. Just like you already had.
Also note that you use remove-item
and remove_item
both, I changed it all to 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>
推荐阅读
- elasticsearch - Elasticsearch 只查找数值
- excel - 如何使用 Excel 在 Outlook 365 Exchange 中引用组或共享日历?
- spring-boot - gradle spring-boot bootDistTar 自定义脚本成tar包
- django - 使用 Django 进行多个 API 调用并循环更新
- html - 如何删除 li 元素之间的空格?
- java - 如何解决错误:java.lang.ClassNotFoundException:io.netty.util.concurrent.GenericFutureListener?
- python - Python:2个相等的数组在相同的操作后不相等
- socket.io - 将 Flutter 应用程序与 socket.io 服务器连接起来
- sql - SQL 查询在 72 小时内花费超过 15.000 美元的回头客
- powershell - TFS 在 PowerShell 上获取具有待定更改的工作区