简体   繁体   中英

How do I delete dynamically created elements in javascript/jquery?

So I'm trying to figure out a way to delete dynamically created elements in my program. I can currently add a pattern above or below the current one.

What I am trying to do though, is to add a delete button right beside the two rows of squares, and then once the user clicks on that button, the particular pattern is removed and all other patterns move into proper positions.

What I have done so far:

var id_num = 1;
var picker = null;
$(function () {
$(document).on('click', ".repeat", function (e) {
    e.preventDefault();
    var $self = $(this);
    var $parent = $self.parent();
    if($self.hasClass("add-bottom")){
      $parent.after($parent.clone(true).attr("id", "repeatable" + id_num));
      id_num = id_num + 1;
      //picker = null;

    } else {
      $parent.before($parent.clone(true).attr("id", "repeatable" + id_num));
      id_num = id_num + 1;
      //picker = null;
    }
});   
});

Any help or feedback is much appreciated!

You can add the delete button inside a container and use it to delete. Can be easy to move the button where you want.

http://codepen.io/anon/pen/QKgBzP

var id_num = 1;
var picker = null;
$(function () {
$(document).on('click', ".repeat", function (e) {
    e.preventDefault();
    var $self = $(this);
    var $parent = $self.parent();
    var newobj=$parent.clone(true).attr("id", "repeatable" + id_num);
    if($self.hasClass("add-bottom")){
      $parent.after(newobj);
      id_num = id_num + 1;
      //picker = null;

    } else {
      $parent.before(newobj);
      id_num = id_num + 1;
      //picker = null;
    }
    newobj.append("<button class=\"remove\"> Remove</remove>");
});   
$(document).on('click', ".remove", function (e) {
    $(this).parent().remove();
});
});

You could look at the parent of the button and force a remove:

var elem = document.getElementById("yourid");
    elem.parentElement.removeChild(elem);

On creation of another repeatableX , you would also be creating a button just for that container I assume.

On that button click you would look at the parent ID for the button, in your case, repeatableX , then tell it to remove that parent, something similar to the above snippet.

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