2012 年推荐的 jQuery 模板? [英] Recommended jQuery templates for 2012?

查看:25
本文介绍了2012 年推荐的 jQuery 模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery 模板已经弃用了一段时间.

我有一些 JavaScript 对象形式的数据,我想将其格式化为 HTML 并附加到 DOM.目前最好的做法是什么?

  1. 我应该构建一个 HTML 字符串吗?
  2. 我是否应该通过 jQuery 创建元素,例如 $('<li>',{id:'my-'+Id}).append($('<span>').text(myText)) ?
  3. jQuery 模板有替代品或成熟替代品吗?

解决方案

这就是我在项目中的做法:

在 HTML 中定义模板:

使用 string.format 替换变量:

var cardTemplate = $("#cardTemplate").html();var template = cardTemplate.format("http://example.com", "链接标题");$("#container").append(template);

string.format:

String.prototype.format = function() {var args = 参数;return this.replace(/{(d+)}/g, function(match, number) {return typeof args[number] != 'undefined'?参数[编号]: 比赛;});};

非常简单,您甚至可以组合模板.

jQuery Templates have been deprecated for some time now.

I have some data in the form of a JavaScript object that I want to format as HTML and append to the DOM. What's the best way of doing that these days?

  1. Should I build up an HTML string?
  2. Should I create elements via jQuery such as $('<li>',{id:'my-'+Id}).append($('<span>').text(myText)) ?
  3. Is there a replacement or mature substitute for jQuery templates?

解决方案

This is how I do it in my projects:

Define a template in your HTML:

<script type="text/template" id="cardTemplate">
<div>
    <a href="{0}">{1}</a>
</div>
</script>

Use string.format to substitute variables:

var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);

string.format:

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

Pretty simple, you can even combine templates.

这篇关于2012 年推荐的 jQuery 模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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