[英]How to remove div element with jQuery
當我想刪除 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>
當我單擊 remove-btn 時,應刪除其父 div 文本字段。 我有這個代碼,但它不起作用。
$(".remove-btn").click(function(){
$(this).parent().remove();
});
謝謝你的幫助。 :)
最常見的原因是您可能試圖在元素加載到 DOM 之前綁定到 click 事件。 嘗試將您的 jQuery 代碼包裝在:
$(document).ready(function() {
// your code here
});
還有.live() function 將綁定到稍后添加到 DOM 的元素。
確保 javascript 在DOM load之后加載。
$(function(){
$(".remove-btn").click(function(){
$(this).parent().remove();
});
});
閱讀您的評論后,您應該這樣做:
$("#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.