简体   繁体   中英

How can I manipulate dynamically created elements wth jquery?

I am a jquery newbie and i am creating boxes with jquery and then "deleting" them. But I want to use the same code to delete the box in the scope of the created element and the scope of a already created element.

Html:

<button id="create">Cria</button>
    <div id="main">
        <div class="box">
            <a class="del-btn" href="#">Delete</a>
        </div>
</div>

JS:

    var box = {

  create: function() {
      var box = $('<div class="box">');
      var delBtn = $('<a class="del-btn" href="#">Delete</a>');
      box.appendTo('#main');
      delBtn.appendTo(box);
  },

  destroy: function(elem) {
    elem.fadeOut();
  } 

}

function deleteBox () {

}

$(function() {

  $('#create').click(function() {
    box.create();
  });

  $('.del-btn').click(function() {
    var elem = $(this).parent();
    box.destroy(elem);  
    return false;
  });

});

If I put the delete event inside the create click event, I just can delete the dynamically created element. If I put it outside, then I can just delete the element in the HTML. I know this is a simple question, but I can't figure out how to solve it. Thanks

You can use delegated-events approach :

$("#main").on("click", ".del-btn", function() {
    var elem = $(this).parent();
    box.destroy(elem);  
    return false;
});

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