You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Meteor中使用#each渲染模板后无法获取数据上下文问题

问题分析与解决

你的代码存在几处问题,导致无法在事件中获取对应数据对象,具体修正如下:

1. 模板与Helper变量名不匹配

模板中使用{{#each items}}遍历数据,但Helper定义的函数名是list,变量名不匹配会导致Blaze无法找到对应数据源。需将Helper名称改为items:

Template.render_array.helpers({
  'items': function(){
    return [
      {name: "AA", description:"A for Apple"},
      {name: "BB", description:"B for Boring"}
    ]
  }
})

2. 数据字段名不匹配

模板里写的是{{this.itemdescription}},但你的数据对象中对应的字段是description,需修正字段名才能正确渲染内容:

<template name="render_array">
  <ul class="list">
    {{#each items}}
      <li>{{this.description}}</li>
    {{/each}}
  </ul>
</template>

3. 事件绑定位置错误

你把点击事件绑定在ul.list元素上,这个元素处于{{#each}}循环外部,对应的上下文是模板根级(空对象),所以this返回空。要获取单个数据项的上下文,需将事件绑定在each循环内的li元素上:

Template.render_array.events({
  'click li': function(event, template){
    console.log(this) // 此时this就是对应的数据对象,比如{name: "AA", description:"A for Apple"}
  }
})

完成以上修正后,点击每个li元素时,控制台就能打印出对应的数据对象了。

内容的提问来源于stack exchange,提问作者user2587676

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:42:05