簡體   English   中英

在 jQuery 中單擊自身內部的元素時,刪除動態生成的元素?

[英]Removing dynamically generated elements, when clicking on an element within itself in jQuery?

單擊其中的按鈕時,如何刪除動態生成的元素塊?

function controlContent(target, trigger) {
    //this will add a new div to target which is an existing html element
    $(trigger).on("click", () => {
        $(target).append(`
            <div class="dynamic-container">
                <button class="remove-btn">Remove the div I am inside</button>
            </div>
        `)
    }

    //this should remove the div that was added when I click the remove button
    $(target).on("click", ".remove-btn", () => {
        $(this).closest(".dynamic-container").remove();
    }
}

使用普通的 function 並使用動態點擊偵聽器,因此您無需每次都創建新的事件列表器。

$(document).on('click', '.remove-btn', function(){
    $(this).closest(".dynamic-container").remove();
})

第一:你應該使用$(document).on("click", target, function(){...}動態生成的元素

第二:parent()一樣簡單

$(document).on("click", target, function(){
  $(this).parent().remove();
 });

例子:

 $(".button1").on("click", function(){ $(".generatedbuttons").append('<div class="green"><button class="button2">Click me to remove me and my parent</button></div>'); }); $(document).on("click", ".button2", function(){ $(this).parent().remove(); });
 .button1 { display:block; float: left; }.green { padding: 10px; background-color: green; display: block; float: left; clear: both; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="button1">Click me to generate buttons</button> <div class="generatedbuttons"> </div>

暫無
暫無

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

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