我无法按照我认为应该在Meteor中运行的方式获取HTML选项。
以下是一个如何使用名为“国家/地区”的集合按钮的示例。
模板
{{#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等......我认为它会“与Meteor一起工作”,但我无法弄清楚如何做到这一点。
这是我正在尝试的,但它无效。
模板
<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表格处理之前,有任何想法吗?
由于 吊杆
答案 0 :(得分:5)
在Meteor中,each
助手调用Meteor.ui.listChunk
(请查看packages / templating / deftemplate.js),它将当前变量视为this
上下文。
换句话说,它是click #country
中的全局上下文,您只能在this._id
块下访问each
,就像在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"));
}
答案 1 :(得分:2)
如果您尝试访问数据上下文,则需要让事件处理程序访问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
答案 2 :(得分:2)
@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);
}
答案 3 :(得分:1)
您正在侦听选择的“点击”事件。你真的想订阅'改变'事件。单击html元素时会出现“单击”。另一方面,从列表中选择一个值后,会触发“更改”事件。
答案 4 :(得分:0)
也许你也可以看看'packages / liveui / liveui.js'。有一个findEventData
函数,它给出了回调this
对象。