简体   繁体   中英

Remove dynamically generated <div> on click

I am trying to a <div> when it is clicked. When I tried with .live() it shows me:

object has no method live()

I am using jQuery version 1.9, so live has been removed.

$(document).ready(function(){
    $('#addhelper').click(function(){
        $('div#containerr').append('<div class ="helpcont"><input type="text" name="helper_caption[]" class="input-large" placeholder="Caption">'+
      '<input type="text" name="helper_url" class="input-large" placeholder="Url">'+
      '<input type="text" name = "helper_source" class="input-large" placeholder="Source"><button class = "remove" type="button">remove</button></div>');
    });

    $("button.remove").on({
        click: function(){
            $(this).remove('div.helpcont');
        }
    });
});
$("#containerr").on('click', '.remove', function(){
  $(this).closest('.helpcont').remove();
});

#containerr = the closest parent that is not added dynamically

click = event (you can add multiple events by separating them with spaces)

.remove = the selector on which to trigger the event


PS: Use selectors like #id instead of element#id . IDs should be unique anyway, so there's no need to do it the slow way, by making jQuery retrieve all DIV elements, and then searching for the one with the given ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM