我已經創建了一個jquery函數,它添加了一個div以及其中的字段。第一次點擊它,它增加了一個div,但是當我第二次點擊時,它增加了兩個div,它應該只添加一個div。jquery添加divs兩次
我在做什麼,是我計數的divs,然後加1,然後附加新計數與字段ID。任何人都可以檢查並告訴爲什麼這會給人意想不到的行爲?
$(".add_product").click(function(e) {
e.preventDefault();
var div_count = $(".product_fields").length;
alert(div_count);
var new_div_count = (div_count + 1);
$(".product_fields").append('<div class="product_divs"><div class="product_fields"><h5>Item ' + new_div_count + '</h5><div class="input-field"><input type="text" id="item_name_"' + new_div_count + '" name="item_name[]" required><label for="item_name_1">Item Name</label></div><div class="row"><div class="col s4"><div class="input-field"><input type="text" id="item_quantity_"' + new_div_count + '" name="item_quanity[]" required><label for="item_quantity_1">Item Quantity</label></div></div><div class="col s4"><div class="input-field"><input type="text" id="item_cost_price_"' + new_div_count + '" name="item_cost_price[]" required><label for="item_cost_price_1">Item Cost Price</label></div></div><div class="col s4"><div class="input-field"><input type="text" id="item_retail_price_"' + new_div_count + '" name="item_retail_price[]"><label for="item_retail_price_1">Item Retail Price</label></div></div></div></div></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col s7 product_field_div">
<div class="product_divs">
<div class="product_fields">
<h5>Item 1</h5>
<div class="input-field">
<input type="text" id="item_name_1" name="item_name[]" required>
<label for="item_name_1">Item Name</label>
</div>
<div class="row">
<div class="col s4">
<div class="input-field">
<input type="text" id="item_quantity_1" name="item_quanity[]" required>
<label for="item_quantity_1">Item Quantity</label>
</div>
</div>
<div class="col s4">
<div class="input-field">
<input type="text" id="item_cost_price_1" name="item_cost_price[]" required>
<label for="item_cost_price_1">Item Cost Price</label>
</div>
</div>
<div class="col s4">
<div class="input-field">
<input type="text" id="item_retail_price_1" name="item_retail_price[]">
<label for="item_retail_price_1">Item Retail Price</label>
</div>
</div>
</div>
</div>
</div>
<div class="action_div"><a href="#" class="add_product">Add new product</a></div>
</div>
Istead我懷疑它是與你的附加不匹配原始的HTML格局的HTML。 –