4

有什么方法可以获取使用生成的选项标签的数据上下文{{#each}}?目前,我使用两种解决方法,具体取决于我正在迭代的数据类型。

案例 1 - 选项光标

<template name="select">
  <select>
    {{#each options}}
    <option value="{{_id}}">{{label}}</option>
    {{/each}}
  </select>
</template>

Options = new Meteor.Collection('options');
Template.select.events({
  'change select': function (e, t) {
    var option_doc = Options.findOne($(e.target).val());
  }
});

案例 2 - 选项数组

<template name="select">
  <select>
    {{#each options}}
    <option>{{label}}</option>
    {{/each}}
  </select>
</template>

var options = [{label: "foo"}, {label: "bar"}];
Template.select.events({
  'change select': function (e, t) {
    var option_doc = options[e.target.selectedIndex];
  }
});

如果这是使用文本输入,thisoption_doc在事件处理程序内。但是,由于 change 事件是在 select 而不是 option 上触发的,this因此是指模板的数据上下文。

4

1 回答 1

0

试试UI.getElementData

来自Meteor 文档

UI.getElementData(el) (客户端)

返回从 Meteor 模板渲染 DOM 元素时使用的数据上下文。

论据

elDOM 元素
由 Meteor 模板渲染的元素

于 2014-08-08T10:52:13.443 回答