Javascript 如何使用手柄在数组索引中使用全局变量
我试图使用全局变量访问数组中的对象。然而,似乎车把不允许你这样做。有办法解决这个问题吗 这是我的代码:Javascript 如何使用手柄在数组索引中使用全局变量,javascript,ember.js,handlebars.js,Javascript,Ember.js,Handlebars.js,我试图使用全局变量访问数组中的对象。然而,似乎车把不允许你这样做。有办法解决这个问题吗 这是我的代码: <!DOCTYPE html> <html> <head> <title>Handlebars.js example</title> </head> <body> <div id="placeholder">This will get replaced by handlebars.j
<!DOCTYPE html>
<html>
<head>
<title>Handlebars.js example</title>
</head>
<body>
<div id="placeholder">This will get replaced by handlebars.js</div>
<script type="text/javascript" src="handlebars-v1.3.0.js"></script>
<script id="myTemplate" type="text/x-handlebars-template">
<table>
<tbody>
<tr><th>testing</th><td> <input type="text"><td></tr>
{{!names[index] is not working}}
------> {{#each names.[index]}}
<tr><th> {{this}}</th><td><input type="text"><td></tr>
{{/each}}
</tbody>
</table>
</script>
<script type="text/javascript">
var source = document.getElementById("myTemplate").innerHTML;
var template = Handlebars.compile(source);
var index=0;
var data = {
names: [
{ name: "foo",id:'id',type:"type"},
{ name: "bar",id:'id' },
{ name: "baz",id:'id' }
]};
document.getElementById("placeholder").innerHTML = template(data);
</script>
</body>
</html>
在这个例子中,我知道我不需要使用全局变量,但是对于我正在使用的代码,我需要使用全局变量。请不要使用JQuery,因为我不能使用它
编辑:这就是我在“每个助手”中尝试做的事情。我正在浏览一个对象的每个属性。为此,我必须在特定索引处选择一个对象,例如名称[0]
Handlebar无法从模板内部访问全局变量。顺便说一下,索引不是全局的。您可能必须在给定给模板的上下文中传递索引
{{each names.[index]}}不会解析为迭代名称[index],而是迭代名称['index'],这不是您想要的。{{each names.[0]}}有效,因为0未转换为字符串
解决方案:
我最喜欢的是,直接在上下文中给出想要的元素名称
template({selected:data.names[index]});
使用自定义帮助器
及
最后,您还可以针对此问题要求更好的解决方案或新功能是否{{!名称[index]不起作用}}有效的把手语法?是的。这是在车把评论。即使删除了那一行,它也不起作用。这一行中的selected是什么意思:template{selected:data.names[index]};它是模板中要迭代的元素的名称:{{each selected}}。。。{{/每个}}。您可以在示例中看到它。当然,您可以将selected更改为您认为最合适的变量名。
Handlebars.registerHelper('at', function(context, index, options) {
if( options.fn ) return options.fn(context[index]);
return context[index];
});
{{#at names index}}{{#each .}}
<tr><th>{{@key}}</th><td><input type="text" value="{{.}}"><td></tr>
{{/each}}{{/at}}