是否有生成HTML与JavaScript最佳实践 [英] Is there a best practice for generating html with javascript

查看:115
本文介绍了是否有生成HTML与JavaScript最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话,返回的JSON对象的数组的Web服务。我想利用这些对象和填充HTML股利。比方说,每个对象都包含一个URL和一个名称。

如果我想生成以下HTML为每个对象:

 < D​​IV>< IMG SRC =网址/>该名< / DIV>
 

是否有这样的最佳实践?我可以看到这样做的几种方法:

  1. 在连接字符串
  2. 创建元素
  3. 使用一个模板插件
  4. 在服务器上生成的HTML,然后通过JSON服务了。
解决方案

选项#1和#2将是你最直接简单的选择,但是,对于这两个选项,你会感觉到性能和维护由建筑物或者字符串或创建DOM对象的影响。

模板是不是所有的不成熟,而你看到它弹出在大多数主要的JavaScript框架。

下面是在 JQuery的模板插件为例,将节省您的性能损失,而且是真的,真的很简单:

 变种T = $ .template('< D​​IV>< IMG SRC =$ {U​​RL}/> $ {名}< / DIV>');

$(选择).append(T,{
     网址:jsonObj.url,
     名称:jsonObj.name
});
 

我说去凉爽的路线(和更高性能,更易于维护),并使用模板。

I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name.

If I wanted to generate the following HTML for each object:

    <div><img src="the url" />the name</div>

Is there a best practice for this? I can see a few ways of doing it:

  1. Concatenate strings
  2. Create elements
  3. Use a templating plugin
  4. Generate the html on the server, then serve up via JSON.

解决方案

Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you're going to feel the performance and maintenance impact by either building strings or creating DOM objects.

Templating isn't all that immature, and you're seeing it popup in most of the major Javascript frameworks.

Here's an example in JQuery Template Plugin that will save you the performance hit, and is really, really straightforward:

var t = $.template('<div><img src="${url}" />${name}</div>');

$(selector).append( t , {
     url: jsonObj.url,
     name: jsonObj.name
});

I say go the cool route (and better performing, more maintainable), and use templating.

这篇关于是否有生成HTML与JavaScript最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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