简体   繁体   English

如何使用 jQuery 删除 div 元素

[英]How to remove div element with jQuery

when I want to remove div element, I have the following code:当我想删除 div 元素时,我有以下代码:

<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>

when i click remove-btn, its parent div text-field should be removed.当我单击 remove-btn 时,应删除其父 div 文本字段。 i have this code but it doesnt work.我有这个代码,但它不起作用。

$(".remove-btn").click(function(){
    $(this).parent().remove();
});

thanks for any help.谢谢你的帮助。 :) :)

The most common cause for this is that you may be trying to bind to the click event before the element has been loaded in the DOM.最常见的原因是您可能试图在元素加载到 DOM 之前绑定到 click 事件。 Try wrapping your jQuery code in:尝试将您的 jQuery 代码包装在:

$(document).ready(function() {
  // your code here
});

There's also the .live() function which will bind to elements which are added to the DOM at a later time.还有.live() function 将绑定到稍后添加到 DOM 的元素。

Make sure your javascript is loaded after DOM load .确保 javascript 在DOM load之后加载。

$(function(){
 $(".remove-btn").click(function(){
    $(this).parent().remove();
 });
});

After reading your comment here is what you should do:阅读您的评论后,您应该这样做:

$("#add-file-field").click(function() {
    $("#text").append("<div class='text-field'><input type='text' /> <input type='button' class='remove-btn' value='remove' /></div>");
});

$(".remove-btn").live('click',function() {
    $(this).parent().remove();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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