JavaScript:我应该如何生成大量HTML? [英] JavaScript: How should I generate a lot of HTML?

查看:86
本文介绍了JavaScript:我应该如何生成大量HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
是否存在使用javascript生成html的最佳实践

Possible Duplicate:
Is there a best practice for generating html with javascript

我想用JavaScript生成网站的大部分内容.

I want to generate large parts of a website with JavaScript.

直接的方法是形成一个包含所有HTML的大字符串:

The straightforward way is to form one large string containing all the HTML:

'<div>'
   + '<span>some text</span>'
   + '<form>'
      + '<input type="text" />'
...

但是当人们不得不以这种风格写几百行时,这变得很烦人.后来不得不更改此类代码的痛苦...

But this gets quite annoying when one has to write a few hundred lines in this style. And the pain when such code has to be changed later on...

您能想到一种更简单的方法吗?

Can you think of an easier way?

推荐答案

将代码段创建为模板,并将其放入不可见的<div>:

Create snippets as templates, put them into an invisible <div>:

<div style="display: none">
   <div id="template1">
      <h2 class="header_identifyingClass">Hello from template</h2>
   </div>
   <div id="template2">
      <span class="content">Blah blah</span>
   </div>
</div>

然后找到它,

document.getElementById("template1"); 

填写其内部值,例如通过XPath或jQuery查找内部元素并填充它们,例如使用element.innerHTML = "Hello from new value",并将其移动或复制到DOM的可见部分.

fill it's internal values, e.g. find inside elements by XPath or jQuery and fill them e.g. using element.innerHTML = "Hello from new value", and move or copy it to the visible part of DOM.

创建多个模板并多次复制以生成许多模板. 不要忘记更改副本的ID以保持其正常工作.

Create multiple templates and copy it multiple times to generate many. Don't forget to change the ID for copies to keep it working.

PS:我想我在

PS: I think I used this approach in the code of JUnitDiff project. But it's buried in XSLT which serves another purpose.

这篇关于JavaScript:我应该如何生成大量HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆