js file
在下面的javascript文件中,无论何时创建新的输入类型,我如何为输入类型创建不同的id。
$(document).ready(function(){
$(".template_charge:first").hide(); //hide template
var charge_count =0; // Total charge types.
var charge_id_no =0; // To assign id and name to charge component
/* Add new item based on hidden template */
$(".add_charge").click(function() {
charge_id_no ++;
charge_count ++;
$('#charge_count').val(charge_count);
var newItem = $(".template_charge:first").clone();
newItem.find("input").attr("id", "chargeType_" + charge_id_no); //rewrite id's to avoid duplicates
newItem.find("input").attr("name", "chargeType_" +charge_id_no);
newItem.find("input").attr("id", "charge_" +charge_id_no); //rewrite id's to avoid duplicates
newItem.find("input").attr("name", "charge_" +charge_id_no);
newItem.show(); //show clone of template
$(".template_charge:last").after(newItem);
bindRemove();
});
/* Bind remove function to last added button*/
function bindRemove() {
$(".remove_charge:last").click(function(e) {
if ($(".remove_charge").length > 1)
$(this).parents(".template_charge").remove();
charge_count--;
$('#charge_count').val(charge_count);
});
}
/* Execute bind-function at startup */
bindRemove();
});
html文件
Html文件,如果是单击添加按钮时正在创建的输入类型。
<input type="hidden" id="charge_count" name="charge_count" value="0"/>
<div class="form-group col-md-12" id="other_charge">
<div class="form-group col-md-12 col-sm-12">
<label for="Other_charges" class="control-label col-md-2">Other Charges</label>
<button id="b2" class="btn btn-info add_charge col-md-10 col-sm-12" type="button">Add</button>
<div class="template_charge col-md-offset-2">
<div class="controls" id="profs">
<div id="field_charge" class="form-group input-append col-md-12">
<input autocomplete="off" class="input form-control col-md-5" id="field3" name="charge1" type="text" placeholder="Charge type" />
<input autocomplete="off" class="input2 form-control col-md-5" id="field4" name="charge2" type="text" placeholder="Charge" min="0" max="100" />
<button class="remove_charge btn btn-danger form-control col-md-2" type="button">X</button>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
...有点猜测,无法看到模板,但模板根可能已经是input
,因此调用find
会返回零长度集,所以不起作用。试试这个......
newItem.find("input").attr(/* etc... */);
......应该读......
newItem.attr(/* etc... */);