如何使用Mustache.js在下拉列表中设置选定的值? [英] How to set a selected value in a dropdown list using Mustache.js?
本文介绍了如何使用Mustache.js在下拉列表中设置选定的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用Mustache.js执行此操作?
Is it possible to do this with Mustache.js?
var data = {"val":"3"},
template = '<select>' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'</select>';
var html = Mustache.to_html(template, data);
$(html).appendTo('body');
推荐答案
val
属性不起作用,因为< select>
从<选项>
s具有选择的
属性。我对Mustache不太熟悉,但应该工作:
The val
attribute doesn't work, because a <select>
takes its value from the <option>
s which have the selected
attribute. I'm not very familar with Mustache, but this should work:
// snip...
var html = Mustache.to_html(template, data);
$(html)
.find('option[value=3]').attr('selected', true)
.end().appendTo('body');
我认为您使用的模板不是惯用的Mustache—它太粗糙了;你实际上并没有模仿任何东西。像这样的东西可能更多Mustache-y:
I think that the template you're using is not idiomatic Mustache — it's too coarse grained; you're not actually templating anything. Something like this might be more Mustache-y:
var template = '<select>{{#options}}' +
'<option value="{{val}}" {{#sel}}selected{{/sel}}>' +
'{{txt}}' +
'</option>' +
'{{/options}}</select>',
data = {options: [
{val: 1, txt: 'uno'},
{val: 2, txt: 'dos'},
{val: 3, txt: 'tres', sel: true}
]};
var html = Mustache.to_html(template, data);
$(html).appendTo('body');
这篇关于如何使用Mustache.js在下拉列表中设置选定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文