[英]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 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. 在创建另一个
repeatableX
,您还将为我假设的那个容器创建一个按钮。
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. 在该按钮上单击,您将查看该按钮的父代ID(在您的情况下为
repeatableX
,然后告诉它删除该父代,类似于上面的代码片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.