javascript 我可以对每个对象属性执行 jquery-tmpl 吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6990585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I do a jquery-tmpl each over object properties
提问by Peter Wilkinson
The template {{each}} directive works great for iterating over an array like this:
模板 {{each}} 指令非常适合迭代这样的数组:
var myArray = ["a","b","c"];
I'm wondering if there is an equivalent for iterating over object properties, i.e.:
我想知道是否有一个等效的迭代对象属性,即:
var myObj = {"propOne": "a", "propTwo": "b", "propThree": "c"};
I'd like a template that would let me output as
我想要一个模板,让我输出为
<ul>
<li><span>propOne</span><span>a</span></li>
.... etc
For bonus points I'd like to use this template from KnockoutJS.
对于奖励积分,我想使用来自 KnockoutJS 的这个模板。
采纳答案by RP Niemeyer
Actually {{each}} will walk through properties on an object. You can do something like this:
实际上 {{each}} 将遍历对象的属性。你可以这样做:
{{each(prop, val) myObj}}
<li><span>${prop}</span> - <span>${val}</span></li>
{{/each}}
Here is a sample in Knockout: http://jsfiddle.net/rniemeyer/rpMsM/
这是 Knockout 中的一个示例:http: //jsfiddle.net/rniemeyer/rpMsM/
If you really want to use the foreach
option of the template binding, then the only real option is to map the object to an array of objects with key/value properties. Something like this: http://jsfiddle.net/rniemeyer/rpMsM/1/
如果你真的想使用foreach
模板绑定的选项,那么唯一真正的选择是将对象映射到具有键/值属性的对象数组。像这样的东西:http: //jsfiddle.net/rniemeyer/rpMsM/1/
回答by Arindam Nayak
You can also use this
你也可以用这个
{{each myObj}}
<li><span>${$index}</span> - <span>${$value}</span></li>
{{/each}}