【发布时间】:2017-12-07 18:09:27
【问题描述】:
我有这个 html 表单:
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="patient_weight">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="patient_weight" id="patient_weight">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
还有来自this link here的这个jQuery脚本:
<script>
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo(".rounded")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
</script>
当然,对 html 进行了更改,但是当我单击每个按钮时没有任何反应,甚至在控制台上也没有错误。这里是my fiddle。
我正在使用 jQuery 3.2.1
编辑 1
我试过这个脚本:
$("button.clone").on("click", function()
{
$('.clonedInput').clone().insertAfter('.clonedInput')
});
它有效,但有两个问题:
- 每个元素的 ID 不递增;
- 如果我有 2 个元素并单击按钮,它们将是 4,然后是 8,然后...
编辑 2
我试过了,问题 2 消失了:
$("button.clone").on("click", function()
{
$('#clonedInput1').clone().insertAfter('#clonedInput1')
});
现在我仍然需要增加 id,以便以后可以使用 Ajax 发送数据。 Here is my updated fiddle.
【问题讨论】:
-
首先,您使用了#clone,因为您已将添加类的类指定为克隆。其次,clone 已经是一个预定义的函数了,你还把它当作类使用?还有很多未使用的类。
-
@HemaNandagopal 查看我的编辑。我不知道为什么有人反对我
-
刚刚看到您的编辑。我认为您的小提琴需要更新?它不起作用。有时人们会投票。它发生了,别担心。
-
请在 30 秒后查看我的编辑,然后我将重新更新小提琴
-
请参阅 EDIT2 和更新的小提琴
标签: javascript jquery html append clone