以下腳本創建最多 4 個的新輸入欄位。我需要知道如何增加 ID,如下所示。
第一次點擊,“var fieldHTML”生成:
<div><input type="text" id="sPhone_1" value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>
第二次點擊:id="sPhone_2" 第三次點擊:id="sPhone_3" 以此類推..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" id="sPhone_" value=""/><a href="javascript:void(0);" ><img src="remove-icon.png"/></a></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x ; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<div class="field_wrapper">
<div>
<input type="text" name="Phone" id="sPhone" value=""/>
<a href="javascript:void(0);" class="add_button" title="Add field"><img src="add-icon.png"/></a>
</div>
</div>
uj5u.com熱心網友回復:
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x ; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
newId = 'sPhone_' x;
document.getElementById('sPhone_').id = newId;
}
});
試試這個。這應該使用初始 id sPhone_ 在 html 中發布 div,然后它獲取該元素并用您新創建的 id 替換 id。
或者您可以創建字串以附加到函式中,如下所示:
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x ; //Increment field counter
var fieldHTML = '<div><input type="text" id="sPhone_"' x 'value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>'; //New input field html
$(wrapper).append(fieldHTML); //Add field html
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474257.html
標籤:javascript html jQuery
上一篇:HTML并排書寫
下一篇:在if陳述句中添加HTML
