我不确定我是否问了正确的问题。但我的应用程序严重依赖 Javascript 和 jQuery 来创建 HTML 文档。所以我有很多这样的“jQuery(”),然后还有很多 div.attr(“id”,“123”)。
那么,有没有更好的方法来做到这一点,或者有一些设计模式来处理这个问题?
非常感谢。
最佳答案
是的,jQuery Templates 。它们使使用 jQuery 构建 html 变得更容易,您可以这样做:
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>
<ul id="movieList"></ul>
<script>
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
并得到:
- 红色 fiddle (1998)
- 大开眼界 (1999)
- 继承(1976)
关于Javascript、jQuery 模式创建 HTML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590735/