Recently writing a project needs to implement a dynamic input function. Originally thought it was very simple, just need to write a method in the front-end js, splicing a string and adding it to html through innerHTML.
code show as below:
for(var i=0;i<3;i++){
j=i+1;
var name="制件"+j;
var value="value"+i;
var str=name+":<input type='text' name='"+value+"' value='' class='form-control'>"
a=a+str;
}
document.getElementById("id").innerHTML=a;
Later, new requirements were put forward, and several inputs needed to be dynamically added. Replace innerHTML with insertAdjacentHTML.
for(var i=0;i<3;i++){
j=i+1;
var name="制件"+j;
var value="value"+i;
var str=name+":<input type='text' name='"+value+"' value='' class='form-control'>"
a=a+str;
}
document.getElementById("work").insertAdjacentHTML('beforeBegin',a);
After using innerHTML, the last added content will be replaced when continuing to add.
insertAdjacentHTML can continue to add based on the last content.
insertAdjacentHTML has four properties:
1. beforeBegin: Insert before the start of the tag
2. afterBegin: Insert after the tag start tag
3. beforeEnd: Insert before the tag end tag
4. afterEnd: Insert after the tag end tag