adding input field dynamically causes problems

2019-08-27 21:22发布

I'm working on a html page and I have a problem when adding a new input field to the form. The problem is that, the content of the other input fields is resetted when the new field is added.

The code for adding a new input text is the following:

var TSLOT = 
[   "<div id=\"TSLOT_n_\">",
    "From: <input type=\"text\" id=\"from_n_\" autocomplete=\"off\">",
    "By letter: <input type=\"text\" id=\"letter_n_\" autocomplete=\"off\">",
    "To: <input type=\"text\" id=\"to0-_n_\" autocomplete=\"off\">",
    "<input type=\"text\" id=\"to1-_n_\" autocomplete=\"off\">",
    "<BR></div>" ].join("");

function addSlotTransition() { 
document.getElementById( "Delta" ).innerHTML += TSLOT.replace( /_n_/g, Delta_size++ ); }

Am I missing something?

1条回答
淡お忘
2楼-- · 2019-08-27 22:07

When you use .innerHTML, it creates a new DOM tree from the parsed innerHTML and rewrites it, so everything not present in the HTML is lost. Use a real append:

 document.getElementById( "Delta" ).insertAdjacentHTML( 'beforeend', TSLOT.replace( /_n_/g, Delta_size++ ) );

JS Fiddle Demo

查看更多
登录 后发表回答