![](/img/trans.png)
[英]jQuery get attribute of clicked element when content is dynamically generated
[英]Jquery: Removing dynamically generated element when modal confirmation button is clicked
例如:
<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
和Cancel
,删除整个(父)项目。 我怎样才能做到这一点? 这是我所做的:
$(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();});
});
但它不起作用。 为什么? 有没有更好的方法?
[编辑]
TS 想要一个模态窗口,这个答案提供了一个替代方案
除了模态窗口,您也可以使用confirm()
。
如果确认,您可以使用parent()
选择跨度的parent()
元素,淡出该元素,然后删除。 就像你已经有了一样。
另请注意,您同时使用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>
这是解决我的问题的方法:
$(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.