自定义绑定 HTML jQuery

custom binding html jquery

本文关键字:jQuery HTML 绑定 自定义      更新时间:2023-09-26

我需要像下面这样...

我的网页将是

<div id="targetdiv">
<div class="Comments30" title="{@something1}"></div>
<div class="{@something2}" title="{@something3}"></div>
<div class="Comments30" title="{@something4}"></div>
</div>

我的 json 将是

var myJson=
{
something1 : value1
something2 : value2
something3 : value3
something4 : value4
}

我想使用 jquery 绑定它们,例如

$('#targetdiv').bindMyJSON(myJson);

我怎样才能做到这一点。我知道它会是这样的

jQuery.fn.extend({
bindMyJSON : function(json){    
}})

你可以用一些 $.fn.renderMyJSON() 来做到这一点,但像 _.template、handlebars 等模板引擎存在是有原因的。

我使用 .replace() 对一些基本的 renderByJson() 插件做了一些小提琴,但请记住,这只会替换要替换的字符串的第一个发现

出现:http://jsfiddle.net/6dece/

基本代码如下所示:

jQuery(function($) {
    $.fn.renderMyJSON = function(json) {
        var $el = $(this);
        $.each(json, function(key, val) {
            $el.html($el.html().replace('{@' + key + '}', val));
        });
    };

    var json = $.parseJSON('{"something1" : "value1","something2" : "value2","something3" : "value3","something4" : "value4"}');
    $('#targetdiv').renderMyJSON(json);
})

下划线.js 有一个很棒的_.template函数,我建议使用,但这里有一种方法可以在下面解决它:

makeTemplate 是一个函数,用于生成插入变量的函数。您可以向它传递一个模板字符串,它将生成一个函数,当使用对象调用该函数时,该函数将插入属性。 首先处理模板通常比每次查找和替换更有效。

var makeTemplate = (function() {
  var escapeMap = {
    ''n'      : '''n', 
    ''"'      : ''''"',
    ''u2028'  : '''u2028',  // line separator
    ''u2029'  : '''u2029'   // paragraph separator
  };
  return function (templateString) {
    // Escape Special Characters
    templateString = templateString.replace(/["'n'r'u2028'u2029]/g, function(index) {
      return escapeMap[index];
    });
    // Replace interpolation ({@foo}) variables with their object counterpart.
    templateString = templateString.replace(/'{@('w+)'}/g, '" + (obj["$1"] || "") + "');
    // Return template function.
    return new Function('obj', 'return "' + templateString + '";');
  };
}());

有了makeTemplate函数后,您可以定义html并使模板函数:

var html = '<div id="targetdiv"><div class="Comments30" title="{@something1}"></div><div class="{@something2}" title="{@something3}"></div><div class="Comments30" title="{@something4}"></div></div>';
var template = makeTemplate(html);
拥有模板函数

后,您可以调用模板函数:

var interpolatedHtml = template({
  something1 : "value1",
  something2 : "value2",
  something3 : "value3",
  something4 : "value4"
});

我要做的是将myJson的键名分配给div元素作为类属性,并迭代targetDiv集合,假设类名是静态且唯一的,则为元素分配相应的值

.html

<div id="targetDiv">
    <div class="something1"></div>
    <div class="something2"></div>
    <div class="something3"></div>
</div>

.js

var container = $("#targetDiv");
$.each(myJson, function(key, value)
{
  container.filter("." + key).attr("title", value);
});