添加/删除div块jQuery [英] Add/removing div block jQuery
问题描述
我正在编写一个脚本,在单击添加按钮后添加div块。
一切都很好,但是在添加第二个增加的块之后。
I'm writing a script to add div block after clicking the add button.
Everything is fine, however after adding second block that incrementing.
例如:第二次点击后总共添加4个块6。
For example: After second clicking that adding 4 block overall 6.
点击删除后删除也是最后一个。
After clicking the removing that is deleting the last one also.
var removeBtn = $("#removeField");
$("body").on("click", "#addField", function(e) {
e.preventDefault();
var room = $(".room-type").first();
var count = removeBtn.data("count");
if (count > 0) {
removeBtn.data("count", count++).attr("data-count", count++);
} else {
removeBtn.data("count", 1).attr("data-count", 1);
}
room.clone(false).appendTo(".room-type");
});
$("body").on("click", "#removeField:not([data-count=0])", function(e) {
e.preventDefault();
var count = removeBtn.data("count");
if (count > 0) {
$(".room-type").data("count", count--).attr("data-count", count--).last().remove();
}
});
HTML
HTML
<div class="form_element select room-type">
<div class="duo_left">
<label class="form_name"><?=pll__('Room type')?></label>
<select name="room-type[]" class="selectpicker multi-fields">
<?if($single != null) :?>
<option value="Single Room">Single Room</option>
<? endif; ?>
<?if($double != null) :?>
<option value="Single Room">Double Room</option>
<? endif; ?>
<?if($deluxe != null) :?>
<option value="Single Room">Deluxe Room</option>
<? endif; ?>
<?if($deluxe_double != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($executive_room != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($gloria_room != null) :?>
<option value="Single Room">Gloria Room</option>
<? endif; ?>
</select>
</div>
<div class="duo_right">
<label class="form_name"><?=pll__('Number')?></label>
<select name="room-number[]" class="selectpicker multi-fields">
<option value="0" selected>0</option>
<? for ($i=1; $i<=10; $i++) : ?>
<option value="<?=$i?>"><?=$i?></option>
<? endfor; ?>
<option value="10+">10+</option>
</select>
</div>
</div>
推荐答案
你需要附加到父div,添加一个额外的div
you need to append to a parent div, add an additional div
就像房间类型
之上的容器一样,并将你的克隆附加到它上面
like "container" on top of your "room-type" and append your clone to it
room.clone().appendTo("#container");
在删除房间类型课程的长度之前
also before removing check the length of your "room-type" class
这里有一个适合你的小提琴
here is a working fiddle for you
https://jsfiddle.net/fxabnk4o/12/
这篇关于添加/删除div块jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!