如何使 html 选择选项在 Meteor 中工作

How do I make the html select options work in Meteor?

本文关键字:Meteor 工作 选项 何使 html 选择      更新时间:2023-09-26

我无法获得HTML选择选项以我认为它在Meteor中的工作方式工作。

下面是它如何与名为"国家/地区"的集合的按钮配合使用的示例。

模板

{{#each get_countries}}
  <button class="btn btnCountryTest">{{iso3}} - {{name}} </button><br />
{{/each}}

客户端事件处理程序

'click .btnCountryTest': function(event){
   console.log('clicked .btnCountryTest this._id: ' + this._id);
}

生成正确的输出,例如。

clicked .btnCountryTest this._id: 39cd432c-66fa-48de-908b-93a874323e2e

现在,我希望能够做的是在从"HTML选择选项"下拉列表中选择项目时触发其他页面活动。 我知道我可以将 ID 放在选项值中,然后使用 Jquery 等...... 我以为它会"只适用于"流星,但我不知道该怎么做。

这是我正在尝试的,但它不起作用。

模板

<select class="input-xlarge country" id="country" name="country">
  {{#each get_countries}}
    <option value="{{iso3}}">{{name}}</option>
  {{/each}}
</select>

处理器

'click #country': function (event) { 
  console.log('Template.users_insert.events click .country this._id: ' + this._id);
 }

它产生

Template.users_insert.events click .country this._id: undefined

显然不是我所期望的。 在我求助于 Jquery 表单处理之前,有人有什么想法吗?

谢谢史蒂夫

在 Meteor 中,each助手调用 Meteor.ui.listChunk(请查看 packages/templating/deftemplate.js),它将当前变量视为this上下文。

换句话说,它是 click #country 中的全局上下文,您只能在each块下访问this._id,就像在 click #country option 事件中一样。

我认为您可以将数据放在HTML数据属性中,并使用jQuery访问它。就像这样——

模板

<select class="input-xlarge country" id="country" name="country">
  {{#each get_countries}}
    <option value="{{iso3}}" data-id={{_id}}>{{name}}</option>
  {{/each}}
</select>

处理

'click #country': function (event) { 
  console.log('Template.users_insert.events click .country this._id: ' + $(event.currentTarget).find(':selected').data("id"));
 }

如果要访问数据上下文,则需要向事件处理程序授予对 template 参数的访问权限,并将其data对象使用。这是顶级数据上下文。

'click #country': function (event, template) { 
    console.log('Template.users_insert.events click .country _id: ' + template.data._id);
}

应该工作。这是我能找到的最好的文档:http://docs.meteor.com/#template_data

>@StevenCannon,我遇到了类似的问题,并在这里找到了解决方案 - http://www.tutorialspoint.com/meteor/meteor_forms.htm。 @DenisBrat是正确的,请侦听更改事件而不是单击事件。

以下是为您修改的解决方案:

'change select'(event) {
    // Prevent default browser form submit
    event.preventDefault();
    var selectedCountry = event.target.value;
    console.log('Template.users_insert.events change select iso3: ' + selectedCountry);
}

您正在侦听所选内容的"单击"事件。您确实想订阅"更改"事件。当您单击 html 元素时,会出现"单击"。另一方面,"更改"事件在您从列表中选择值后触发。

也许你也可以看看'packages/liveui/liveui.js'。有一个 findEventData 函数,它为对象提供回调this