如何使用 Mustache.js 在下拉列表中设置选定的值?
可以用 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');
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');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
val
属性不起作用,因为我认为您使用的模板不是惯用的 Mustache - 它的粒度太粗;你实际上并没有模板化任何东西。像这样的东西可能更符合小胡子的风格:
演示 →
The
val
attribute doesn't work, because a<select>
takes its value from the<option>
s which have theselected
attribute. I'm not very familar with Mustache, but this should work: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:
Demo →
如果之后不想修改数组或 DOM 树,可以使用函数:
if you do not want to modify the array or DOM tree afterwards you can use a function:
我使用这个技巧来保持简单:
通过这种方式,您可以转换这种数据:
使用这种胡子模板:
像这样:
这仍然很容易阅读!唯一需要注意的是你不能有“.”。在你的价值观中。
I use this hack to keep it simple:
In this way, you can transform this kind of data:
With this kind of Mustache Template:
Like this:
Which still really easy to read! The only caveat is that you can't have a '.' in your values.
我知道,我有点晚了,仅供将来参考:
I little bit late, I know, just for future reference: