Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将对象作为参数传递给把手模板中的onclick方法_Javascript_Json_Handlebars.js - Fatal编程技术网

Javascript 将对象作为参数传递给把手模板中的onclick方法

Javascript 将对象作为参数传递给把手模板中的onclick方法,javascript,json,handlebars.js,Javascript,Json,Handlebars.js,我有一个JSON,看起来像这样: { list: [ { name: 'AAA', id: 1, age: 34 }, { name: 'BBB', id: 2, age: 24 } ] } <ul> {{#each list}} <li onclick="someFunc({{this}})"&g

我有一个JSON,看起来像这样:

{
list: [
        { name: 'AAA',
          id: 1,
          age: 34
        },
        { name: 'BBB',
          id: 2,
          age: 24
        }
      ]
}
<ul>
    {{#each list}}
        <li onclick="someFunc({{this}})">{{name}} ({{age}}) </li>
    {{/each}}
</ul>
 ... onclick="someFunc( {name: 'AAA', id: 1, age: 34} )" ...
还有这样一个模板:

{
list: [
        { name: 'AAA',
          id: 1,
          age: 34
        },
        { name: 'BBB',
          id: 2,
          age: 24
        }
      ]
}
<ul>
    {{#each list}}
        <li onclick="someFunc({{this}})">{{name}} ({{age}}) </li>
    {{/each}}
</ul>
 ... onclick="someFunc( {name: 'AAA', id: 1, age: 34} )" ...
而我希望它是这样的:

{
list: [
        { name: 'AAA',
          id: 1,
          age: 34
        },
        { name: 'BBB',
          id: 2,
          age: 24
        }
      ]
}
<ul>
    {{#each list}}
        <li onclick="someFunc({{this}})">{{name}} ({{age}}) </li>
    {{/each}}
</ul>
 ... onclick="someFunc( {name: 'AAA', id: 1, age: 34} )" ...

如何解决此问题?

发布供将来参考:

我从这里得到了答案:

原来Handlebar在粘贴到模板之前对数据进行了toString。我所要做的就是注册一个helper方法,将其转换回json

Handlebars.registerHelper('json', function(context) {
    return JSON.stringify(context);
});

<li onclick="someFunc({{json this}})">{{name}} ({{age}}) </li>
handlebar.registerHelper('json',函数(上下文){
返回JSON.stringify(上下文);
});
  • {{{name}}({{age}})

  • Alt:我通常使用data*属性来表示我想在这种场景中渲染的属性。这是什么意思?我应该注册自己的助手方法吗?
  • {{{name}}({{age}})
  • 这将如何解决我的问题?我无法正确获取someFunc()中的数据。相反,它看起来像是在对象上执行tosString,并发送meIt不是一个直接的答案,我应该提到,我将值作为数据属性呈现,在li元素的click处理程序中,我从事件源元素读取数据属性,并将值传递给需要调用的任何函数(就像你的情况一样有趣)。