2013-07-29 31 views
0

這裏只刪除一個DIV是JsFiddle與查詢

我有一個按鈕,將添加新的標題,文本框,當它的點擊一個鏈接。

但是當我點擊刪除鏈接。它會刪除添加的每個新項目。

HTML:

<div id='main'> 
Top of Boby 
    <div id='main_1'> 
     <div> 
      <h3> Item</h3> 
      <input type="text" /> 
     </div> 
    </div> 
</div> 

JS:

$(function() { 
    $('.AddItem').click(function() { 
     $('div#main_1').append("<div><h3>Item</h3><input type='text' class='remove_skill'/><a href=''>Remove</a</div>"); 
    }); 
}) 
$(function() { 
    $('.remove_skill').click(function() { 
     $(this).remove(); 
    }); 
}) 
+0

'.remove_skill'在哪裏? – MahanGM

+1

我建議你使用'.innerHTML'甚至是'.html()'而不是'.append()'。這在性能方面更好。 –

回答

2

你發佈的代碼的問題是沒有lin ks在您撥打$('.remove_skill').click的那一刻存在,因此您無法爲其添加事件偵聽器。

我推薦一步一步的方法。創建,添加行爲,附加到文檔。

$('.AddItem').click(function() { 
    var new_element = $('<div class="item"><h3>Item</h3><input type="text"/><a class="remove" href="#">Remove</a></div>'); 
    new_element.find(".remove").click(remove_item); 
    $('div#main_1').append(new_element); 
}); 

function remove_item() { 
    $(this).closest(".item").remove(); 
    return false; 
} 

我建議<a href="#">用於JavaScript處理的鏈接。使用封閉

替代解決方案:

$('.AddItem').click(function() { 
    var new_element = $("<div class="item"><h3>Item</h3><input type='text'/><a class="remove" href="#">Remove</a</div>"); 
    new_element.find(".remove").click(function() { 
     new_element.remove(); 
    }); 
    $('div#main_1').append(new_element); 
}); 
4

2問題..

你從來沒有定義的類錨。將類添加到錨

您需要remove the enclosing div和n ot the anchor.使用.closest

還需要委託作爲被動態添加

$('#main').on('click', '.remove_skill', function (e) { 
     e.preventDefault(); 
     $(this).closest('div').remove(); 
    }); 

Check Fiddle

元素事件
+0

另外:在'append()'過程中,** anchor **標籤沒有正確關閉。 –

+0

是真的..也必須修復 –

0

您的問題是你的 「刪除」 是在 'A' 的標籤。這會導致頁面重新加載,並刪除您之前的所有更改。