[英]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.当点击remove-item
类时,当用户点击确认时,将显示一个带有两个按钮Confirm
和Cancel
,删除整个(父)项目。 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 TS 想要一个模态窗口,这个答案提供了一个替代方案
Instead of a modal window, you can use confirm()
too.除了模态窗口,您也可以使用confirm()
。
If that is confirmed, you select the parent of the span, by using parent()
, fade that element out, and remove.如果确认,您可以使用parent()
选择跨度的parent()
元素,淡出该元素,然后删除。 Just like you already had.就像你已经有了一样。
Also note that you use remove-item
and remove_item
both, I changed it all to remove_item
另请注意,您同时使用remove-item
和remove_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>
Here's what solved my problem:这是解决我的问题的方法:
$(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();});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.