首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >按钮上的Twitter Bootstrap onclick事件-单选

按钮上的Twitter Bootstrap onclick事件-单选
EN

Stack Overflow用户
提问于 2012-02-13 23:12:31
回答 6查看 119.9K关注 0票数 64

我有一个Twitter Bootstrap buttons radio,并将一个onclick事件挂接到它。但是我如何检查哪些按钮被触发了呢?

我的第一个想法是简单地检查“active”类,但这应该创建一个竞争条件(结果取决于首先处理Twitter Bootstrap事件还是我自己的onclick事件)。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-06-21 20:15:54

这是一个非常烦人的问题。我最终使用的是:

首先,创建一组没有data-toggle属性的简单按钮。

代码语言:javascript
复制
<div id="selector" class="btn-group">
    <button type="button" class="btn active">Day</button>
    <button type="button" class="btn">Week</button>
    <button type="button" class="btn">Month</button>
    <button type="button" class="btn">Year</button>
</div>

接下来,编写一个事件处理程序,通过“激活”单击的单选按钮并“停用”所有其他按钮来模拟单选按钮的效果。(编辑:评论中的集成Nick的更干净的版本。)

代码语言:javascript
复制
$('#selector button').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    // TODO: insert whatever you want to do with $(this) here
});
票数 76
EN

Stack Overflow用户

发布于 2015-02-19 17:51:20

我看到了很多复杂的答案,而这在Bootstrap 3中非常简单:

步骤1:使用the official example code创建您的单选按钮组,并为容器提供id:

代码语言:javascript
复制
<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>

第2步:使用此jQuery处理程序:

代码语言:javascript
复制
$("#myButtons :input").change(function() {
    console.log(this); // points to the clicked input button
});

Try the fiddle demo

票数 76
EN

Stack Overflow用户

发布于 2012-02-14 07:23:37

我会使用一个更改事件,而不是像这样的单击:

代码语言:javascript
复制
$('input[name="name-of-radio-group"]').change( function() {
  alert($(this).val())
})
票数 23
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9262827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档