【问题标题】:How can I access the context of an option in Meteor?如何访问 Meteor 中选项的上下文?
【发布时间】:2014-10-01 07:38:36
【问题描述】:

有什么方法可以获取使用{{#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];
  }
});

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

【问题讨论】:

    标签: javascript meteor spacebars


    【解决方案1】:

    试试UI.getElementData

    来自Meteor docs

    UI.getElementData(el) (客户端)

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

    参数

    el DOM 元素
    由 Meteor 模板渲染的元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      相关资源
      最近更新 更多