javascript - 删除附加的父元素

标签 javascript jquery

我有一个列表生成器,它可以附加项目,但也可以将垃圾桶项目附加到所制作的每个列表项目中。我在垃圾桶上有一个函数,当单击它时应该删除父元素,但它不起作用。

这是我正在尝试做的事情的简单版本

JSFiddle

$('button').click(function() {
    $('#contain').append('<div class="div"></div>').append('<div class="nested"></div>');
});

$('.nested').click(function() {
    $(this).parent().remove();
});

如何仅删除被单击的嵌套 div 的父元素?

最佳答案

使用on()因为您正在动态附加的元素上调用事件。

$('body').on('click', '.nested', function(){
   $(this).parent().remove();
});

我们也可以使用 $('#contain') 代替 $('body')

$('button').click(function() {
	$('#contain').append('<div class="div"></div>').append('<div class="nested"></div>');
});

$('body').on('click', '.nested', function() {
	$(this).parent().remove();
});
.div {
  width: 100px;
  height: 50px;
  background: #000;
  margin-top: 50px;
}
.nested {
  width: 50px;
  height: 25px;
  background: red;
  z-index: 100;
  margin-top: -25px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add
</button>

<div id="contain">
</div>

关于javascript - 删除附加的父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732055/

相关文章:

jquery - 如何在选项更改时创建 div?

javascript - 未捕获类型错误 : fn is not a function in chart. js

javascript - 简单的 SVG 网格在 IE 10 和 IE 11 中不显示

jquery - 在没有php的情况下显示文件夹中的所有图像

javascript - 是否可以创建与 Java 等效的 UUID 生成器的 Javascript 版本

javascript - 如何使滚动到仅特定于桌面 View 的 ID 并在移动 View 上默认它?

javascript - 如何从 Float32Array 创建矢量原型(prototype)?

javascript - Angular 追加 ng-repeat 不起作用

javascript - 验证 sendKeys 导致页面对象文件导致未定义错误(Protractor)

jQuery 更改样式表(如主题切换器),不在 IE 中加载 CSS