How to remove an element that is added dynamically in Javascript

前端 未结 5 1275
鱼传尺愫
鱼传尺愫 2020-12-28 16:40

I have the following code to create some element:

<
相关标签:
5条回答
  • 2020-12-28 17:10

    Because it's dynamic content, you can't bind events like the static content, it will not bind to the elements because they don't appear at the time you bind.

    So you should bind event like this:

    $('#parent').on('click', 'a.remove_block', function(events){
       $(this).parents('div').eq(1).remove();
    });
    
    0 讨论(0)
  • 2020-12-28 17:15

    You need to use event delegation for dynamically added elements. Even though you have used .on() the syntax used does not use event delegation.

    When you register a normal event it adds the handler to only those elements which exists in the dom at that point of time, but when uses event delegation the handler is registered to a element which exists at the time of execution and the passed selector is evaluated when the event is bubbled upto the element

    $(document).on('click', '.remove_block', function(events){
       $(this).parents('div').eq(1).remove();
    });
    
    0 讨论(0)
  • 2020-12-28 17:15
    $('a.remove_block').on('click',function(events){
      $(this).parents('.parent_div').remove();
      return false;
    });
    
    0 讨论(0)
  • 2020-12-28 17:18

    You can use the .live for this:

    $('body').live('click','#idDinamicElement', function(){
       // your code here
    });
    
    0 讨论(0)
  • 2020-12-28 17:28

    I had the situation where the dynamic element to remove wasn't a descendant of my event listener:

    siteSel.on('select2:select', function (e) {
          // remove some other dynamic element on page.
    });
    

    Solution I found was using when() method.

    siteSel.on('select2:select', function (e) {
          let dynamicElement = $('.element');
          $.when(dynamicElement).then(dynamicElement.remove());
    });
    
    0 讨论(0)
提交回复
热议问题