javascript - 在模板化之前修改 html

标签 javascript jquery templates mustache

我正在使用 Mustache 模板脚本来呈现我的 JSON 值。 我想知道:由于我需要将 data 绑定(bind)到我正在渲染的 html ,因此有一种方法可以将 .data() 应用于我要渲染的对象

我用一些代码更好地解释它:

var temp = $("#template").html(),
     obj = Mustache.render(temp,this);
  //I want to bind data to obj before it gets appended
  $('#appended').append(obj);

最佳答案

在附加 obj 之前或之后修改它。

var temp = $("#template").html(),
    obj = Mustache.render(temp,this);

$(obj).data("foo","bar").appendTo('#appended');

var temp = $("#template").html(),
    $obj = $(Mustache.render(temp,this));

$('#appended').append($obj)
$obj.data("foo","bar");

如果您的 html 不以标记开头,则必须先解析它。

var temp = $("#template").html(),
    $obj = $( $.parseHTML( Mustache.render(temp,this) ) );

$('#appended').append($obj)
$obj.data("foo","bar");

关于javascript - 在模板化之前修改 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16401512/

相关文章:

jquery - 在 jQuery 中获取最高后代后代

javascript - 假设我有一个包含 500 个缩略图的列表,后跟标题。当用户向下滚动时如何加载图像? (JQuery)

c++ - 如何将零大小的数组传递给模板函数

javascript - 如何中断输入的 javascript 操作并开始新操作

javascript - javascript 中的 .all 或 Jquery 中的 .all 替代品是什么

c++ - 如何用 "float (*fSqrt)(float)"替换 "std::function<float(float) fSqrt>"?

javascript - 一次保持一个 Leaflet 侧边栏打开

javascript - 无法将数据列表动态填充到表中

javascript - Android 4.4.x WebView 使用 location.reload() 时在浏览器中打开一个选项卡

javascript - 尝试在 ember 中查找记录和销毁记录时,DELETE 请求在 GET 请求之前完成