开发者

Mustache JS templating and unknown properties

I'm trying to use mustache JS templates dynamically. I'll have an array of templates like so:

var tmpls = [
   '<p>{{name}}</p>',
   '<p><b>{{car}}</b></p>'
];

and then I want to pick the correct template based on the index of something... which I can do like:

var stuff = {
      name: 'bob'
}

$.mustache(tmpls[index], stuff);

but I'm not quite sure how to fill the values based on something else such as input IDs and their valu开发者_C百科es:

<input type="text" id="name" value="Bob" />
<input type="text" id="car" value="Corsa" />

$.mustache(tmpls[index], {
    $('input').eq(0).attr('id') : $('input').eq(0).val()
});

I guess I'm trying to create an object to pass mustache dynamically. The property names are the IDs of the input fields and the values are from the input field.

Is this possible?

Thanks, Dom


One possible way to build your stuff object is by iterating through the elements using .each():

var stuff = {};

$('input').each(function() {
    stuff[$(this).attr('id')] = $(this).val();
});

$.mustache(tmpls[index], stuff);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜