jquery remove parent not working on dynamically created divs

后端 未结 3 1711
傲寒
傲寒 2021-02-14 12:06

im trying to use jquery in order to make a button remove its parent div.

my markup:

相关标签:
3条回答
  • 2021-02-14 12:40

    I recently was running into an issue with $.on() that unclear and very similar to this application, as most "remove this's parent" functions are.

    To illustrate with this question's example:

    $('.web_store_fields').on('click', '.button_remove_web_store', function(e){
        $(this).parent().remove();
    });
    

    the big catch here is the second parameter. you must select the container $('.container') and pass the element selector of the 'button' as the second parameter to the .on function. so a definition(of sorts)

    $('.container').on('click', '.myremovebutton', function(e){
        $(this).parent().remove();
    });
    
    0 讨论(0)
  • 2021-02-14 12:58

    Do not use a live handler -- it has been deprecated in jQuery 1.7 and removed in jQuery 1.9 -- a breaking change for a great many people.

    Instead, use the on handler, which is the recommended way now:

    $(document).on('click', '.button_remove_web_store', function() {
        $(this).parents("div:first").remove();
    });
    
    0 讨论(0)
  • 2021-02-14 13:04

    Use a delegated handler (on) with the class as the selector so that any new buttons that get added later will still work.

    $('body').on('click', '.button_remove_web_store', function() {
        $(this).parents("div:first").remove();
    });
    
    0 讨论(0)
提交回复
热议问题