在JavaScript中使用HTML代码片段(jQuery) [英] Using an HTML snippet for a template in JavaScript (jQuery)

查看:124
本文介绍了在JavaScript中使用HTML代码片段(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个小应用程序,它向我的服务器请求用户信息,并使用特殊模板显示它们。



起初,我只对硬编码的小片段在jQuery中:

  $(< li>< div class ='outer'>< table>< tr>< td rowspan = 2 class ='imgcontainer'>< img class ='thumb'/>< / td>< td>< span class ='username'/>< / td> < / div>< / tr>< tr>< td>< span class ='name'/>< / td>< / tr>< / table>< / div>< / li> )

我多次克隆它。



<这是丑陋的,我希望它有语法突出显示和whatnot,所以它会更好的在HTML文件本身。



另外,它会使合并更容易,所以有人可以改变一两行。



有没有这样的模式?我可以把它放在HTML文件中,我包含这个JS(只有一个),并使用CSS隐藏。



我想到的第三个选项是只是创建一个单独的HTML文件,并从服务器jQuery请求分开。这种技术使用得多吗?



另外,有什么术语可以用来描述我在做什么? (很难问一个概念,我不知道名字的问题)

解决方案

我给出了类似的答案今天早些时候。你在找什么叫做微模板。 John Resig在他的博客上发布了这个。基本上你可以得到一个json数据集,并将一个模板应用到数据中来创建html并更新DOM。


I currently am working on a little app that requests user info from my server and displays them using a special template.

At first, I just hardcoded the little snippet in jQuery:

 $("<li><div class='outer'><table><tr><td rowspan=2 class='imgcontainer'><img class='thumb'/></td><td><span class='username'/></td></tr><tr><td><span class='name'/></td></tr></table></div></li>")

I clone it several times.

It's ugly and I want it to have syntax highlighting and whatnot, so it would be better for me to have it in the HTML file itself.

Also, it will make merges easier so somebody can just change a line or two.

Is there a pattern for this? Am I OK putting it in the HTML file that I include this JS in (there's only one), and making it hidden using CSS.

The third option I thought of is just creating a separate HTML file and having jQuery request that from the server to keep it separate. Is this technique used much?

Also, is there any term I can use to describe what I'm doing? (It's harder to ask a question for a concept I don't know the name for)

解决方案

I gave a similar answer on SO earlier today. What you are looking for is called micro-templates. John Resig posted this on his blog. Essentially you can get a json dataset and apply a template to the data to create html and update the DOM.

这篇关于在JavaScript中使用HTML代码片段(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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