javascript - 单选按钮上的 Bootstrap-3 Meteor 事件

标签 javascript radio-button meteor twitter-bootstrap-3

所以我试图让事件点击单选按钮( meteor )。

我在模板事件(客户端 js 文件)中做的:

Template.Questions.events({
 'click #public_btn' : function (){
  console.log('1');
  // something
 },

 'click #private_btn' : function (){
  console.log('2');
  // something
 }

在 html 客户端文件中我有单选按钮:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary active">
      <input type="radio" name="privacy_options" value="public" id="public_btn"> Public
    </label>
    <label class="btn btn-primary">
      <input type="radio" name="privacy_options" value="private" id="private_btn"> Private
    </label>
  </div>

只要 div 获得 data-toggle="buttons" 广告,click 事件就不会触发

>

有办法解决这个问题吗?

最佳答案

请注意,从 Meteor 0.8 开始,模板事件将与 jQuery 触发的事件一起正常工作。

所以正确的解决方案是绑定(bind)到 change 事件:

Template.Questions.events({
  'change #public_btn' : function (){
   console.log('1');
  // something
 },

'change #private_btn' : function (){
   console.log('2');
   // something
}

首先,该事件实际上是 input:radio 上的 change 事件(在撰写本文时不是 click)

其次,Meteor (0.7.0) 使用它自己的事件引擎,它不会捕获 jQuery 触发的事件,例如。 $(元素).trigger('改变')

如果你看一下 bootstrap source它表明 toggle 按钮触发了一个 jQuery/合成事件。

因此您需要绑定(bind) jQuery 事件处理程序,这是我发现的最有效的方法,是在模板创建时执行此操作 - 但基于 document.body 而不是实际元素 - 如它将在每次渲染时被替换。

Template.Questions.created = function(){
  // must bind to `document.body` as element will be replaced during re-renders
  // add the namespace `.tplquestions` so all event handlers can be removed easily
  $(document.body).on('change.tplquestions', '#public_btn', function(e){
     // handler
  });
  // add the namespace `.tplquestions` so all event handlers can be removed easily
  $(document.body).on('change.tplquestions', '#private_btn', function(e){
     // handler
  });
 };
 Template.Questions.destroyed = function(){
   // remove all event handlers in the namespace `.tplquestions`
   $(document.body).off('.tplquestions');
 }

关于javascript - 单选按钮上的 Bootstrap-3 Meteor 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657960/

相关文章:

javascript - Onsubmit 事件拒绝触发

javascript - 无法创建输入元素并添加数据集 : Cannot set property of undefined

javascript - 重写 jQuery 函数以与 Meteor.js 配合使用

meteor - 如何在HTML Meteor中检查移动/网络?

jsf-2 - 带有所需单选按钮的 PrimeFaces 数据表

javascript - 我如何访问 Template.x.rendered 中的 iron-router 路径变量?

Javascript 将选择器的文本内容分配给表单输入值

javascript - jsTestDriver + Nant = 测试目录问题

html - 分离标签和输入

css - 使用 css 自定义单选按钮