[英]how to add and remove div using jquery
我正在制作一個場景,用戶可以通過單擊“添加”按鈕添加“刪除”選項的新行。 如果他們單擊“刪除”按鈕,整個行將被刪除。 我已經為它編了腳本。 但是,它並沒有完美運作。 請注意我的小提琴: http : //jsfiddle.net/learner73/gS8u2/
我的問題是:
(1)如果用戶單擊“添加”按鈕,將添加一個新行。 非常好。 但是,它已經低於“添加”按鈕。 我想,新行將添加到“添加”按鈕上方,我的意思是“添加”按鈕應始終位於底部。
(2)在我的代碼中,如果用戶單擊先前創建的行上的“刪除”按鈕,則將刪除整行。 非常好。 但是,當他們點擊動態創建的行上的“刪除”按鈕時,什么都不會發生!
HTML:
<div class="optionBox">
<div class="block">
<input type="text" /> <span class="remove">Remove Option</span>
</div>
<div class="block">
<input type="text" /> <span class="remove">Remove Option</span>
</div>
<div class="block">
<span class="add">Add Option</span>
</div>
</div>
jQuery的:
$('.add').click(function() {
$('.optionBox').append('<input type="text" /><span class="remove">Remove Option</span>');
});
$('.remove').click(function() {
$(this).parent('div').remove();
});
您需要在刪除鏈接代碼上使用事件委派:
$('.add').click(function() {
$('.block:last').before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
});
$('.optionBox').on('click','.remove',function() {
$(this).parent().remove();
});
此外,您沒有添加完整的div塊以匹配您擁有的其他代碼。 你省略了<div class="block">
並且只添加了輸入和范圍。
API: .before
https://api.jquery.com/before/
希望休息符合你的需要:)
碼
$('.add').click(function () {
$(this).before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
});
$(document).on('click', '.remove', function () {
$(this).parent('div').remove();
});
編輯http://jsfiddle.net/amdzakir/gS8u2/38/檢查所有輸入字段是否都填充了值。
$('.add').click(function() {
flag = true;
$('input').css('border-color','green');
$('input').each(function(){
if ($.trim($(this).val())===''){
$(this).css('border-color','red');
flag = false;
}
});
if(flag){
$(this).before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
}
});
$(document).on('click','.remove',function() {
$(this).parent().remove();
});
試試這個:
$('.remove').click(function() {
$(this).closest('div').remove();
});
$('.add').click(function() {
$('.block:last').after('<input type="text" /><span class="remove">Remove Option</span>');
});
這是一種方式 - http://jsfiddle.net/gS8u2/3/
$('.add').click(function () {
$('.block:last').before(' <div class="block"><input type="text" /><span class="remove">Remove Option</span></div>'); // make sure to add the div too
});
$('body').on('click', '.remove', function () { // use event delegation because you're adding to the DOM
$(this).parent('.block').remove();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.