当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Better way to dynamically create HTML form

问题描述:

I need to dynamically create HTML form. So I can to it using 2 approaches:

1) Use JS to create form

 var myId = document.createElement("input");

myId.setAttribute("type", "hidden");

myId.setAttribute("name", "myId" + index);

myForm.appendChild(myId);

and so on..

2) Use innerHTML and writing valid HTML code:

 document.getElementById("myForm").innerHTML +=

'<input type="hidden" name="myId' + index + '"/>';

What approach is better? What is usually way to dynamically create form? For me second approach is more readable

网友答案:

Creating dynamic forms by concatenating string in javascript becomes unmanageable as the HTML size begins to grow. The recommended approach is to use a template engine to create dynamic HTMLs. Handlebars.js is one of the more popular template engines out there. There's also a site that helps you choose a template engine for your need.

网友答案:

second approach is the best because it gives you the possibility to verify the exact composition of the page. at least in my opinion.

分享给朋友:
您可能感兴趣的文章:
随机阅读: