我有一些Jquery,我用克隆div,里面的div是一个输入,做一个计算。克隆格与新计算器的新divs
当我克隆div并创建一个新的div时,计算不适用于新的div。我知道这个计算只能按照我写的方式进行。我搜索了,但找不到我在找什么。
我也有一个问题,当我在输入中添加一个数字的计算工作的第一个div,但它也删除我的按钮。
如何为每个新克隆的div创建新计算? 如何停止计算删除我的添加/删除按钮?
function clone() {
$(this).parents(".clonedInput").clone()
.appendTo("body")
.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();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
// calculator
$(document).ready(function() {
$(".calculate").bind("keyup change", function(e) {
var cabwidth = parseFloat($("#cabwidth").val()) || 0;
var ply = 1.4375;
var value = cabwidth - ply;
if (!isNaN(value) && value !== Infinity) {
$("#sum").text(value);
}
});
});
body {
padding: 10px;
}
.clonedInput {
padding: 10px;
border-radius: 5px;
background-color: #def;
margin-bottom: 10px;
}
.clonedInput div {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput1" class="clonedInput">
<input type="text" class="calculate" id="cabwidth" placeholder="Cabinet Width">
<div id="sum" />
<div class="actions">
<button class="clone">Add</button>
<button class="remove">Remove</button>
</div>
</div>
下面是一个例子的jsfiddle:jsfiddle
请注意,使用_id_克隆节点会导致_id loss_或_invalid html_(因为id应该是文档唯一的)。此外,克隆节点不会克隆任何事件侦听器;这些将需要重新连接到克隆节点 –
,所以我应该使用类而不是? – AlwaysLearning
为有效的HTML,是的。你应该只有唯一的ID – jasonflaherty