从 html 文件的数组中获取元素

Get element from array from html-file

我正在使用带有 blaze.js 和 mongodb 的 meteor(版本 1.8)。

我正在尝试在 html 文件中使用如下所示的数组元素:

{{#each name in chatMeta.lastWhisp}}
 <div class="WhisperCharacter">
  {{name}}  
 </div>
{{/each}}

此查询的相应助手如下所示:

chatMeta() {
return ChatMeta.findOne({});
},

被查询的集合有一个数组“lastWhisp”

"lastWhisp": ["StringA", "StringB"]

我正在尝试使用事件处理程序获取 {{name}} 的信息:

  'click .WhisperCharacter'(event, template) {
    alert(this.name); //<- Wrong
  },

通常,我可以使用 {{each}} 把手上的 this.x 检索数据,但这似乎只有在我查询每个文档时才有效,而不是在单个文档中查询数组文档。

我尝试了很多时髦的东西,比如 this.lastWhisp.name 等。基本上是猜测。我无法理解它需要什么来检索 {{each}} 车把的信息。有人可以帮助我了解它在这种情况下的工作原理吗?

谢谢!

事件本身没有关于 name 的信息,因为它仅表示您单击了 DOM 元素。

要传输此值,您可以使用 data-* data attribute:

{{#each name in chatMeta.lastWhisp}}
 <div class="WhisperCharacter" data-name="{{name}}">
  {{name}}  
 </div>
{{/each}}

然后您可以使用事件目标上的内置 jQuery .data method 轻松地从事件中读取数据属性:

'click .WhisperCharacter'(event, template) {
  const $target = template.$(event.currentTarget)
  const name = $target.data('name')
  alert(name)
},