Dynamically generate input input box

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325252863&siteId=291194637