更新时间:2023-11-29 11:31:52
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');