簡體   English   中英

Jquery:單擊模態確認按鈕時刪除動態生成的元素

[英]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類時,當用戶點擊確認時,將顯示一個帶有兩個按鈕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();});


    });

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

[編輯]
TS 想要一個模態窗口,這個答案提供了一個替代方案


除了模態窗口,您也可以使用confirm()

如果確認,您可以使用parent()選擇跨度的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();});


    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM