【问题标题】:Bootstrap-3 Meteor event on radio buttons单选按钮上的 Bootstrap-3 Meteor 事件
【发布时间】:2014-03-06 15:33:24
【问题描述】:

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

我在做模板事件(客户端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 事件就不会触发

有没有办法解决这个问题?

【问题讨论】:

  • 不应该是这样的$('#public_btn').click(function (){});
  • @SumanBogati 虽然您可以使用这种 jquery 样式来定义事件,但它不是很好,因为当您更改模板/切换路线时,它将不再起作用

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


【解决方案1】:

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

所以正确的解决方案将只是绑定到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 触发的事件,例如。 $(element).trigger('change')

如果您查看bootstrap source,它会显示toggle 按钮会触发一个 jQuery / 合成事件。

所以你需要绑定 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');
 }

【讨论】:

  • 我可以把你的答案加两次。很清楚也很有用,谢谢你花时间:)
猜你喜欢
  • 2013-08-02
  • 1970-01-01
  • 2016-08-12
  • 2013-12-03
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
  • 2013-08-08
相关资源
最近更新 更多