【问题标题】:Twitter Bootstrap onclick event on buttons-radio按钮收音机上的 Twitter Bootstrap onclick 事件
【发布时间】:2012-03-04 23:47:06
【问题描述】:

我有一个 Twitter Bootstrap 按钮收音机并将 onclick 事件挂钩到它。但是如何检查哪些按钮被触发了?

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

【问题讨论】:

    标签: javascript jquery twitter-bootstrap twitter-bootstrap-3 jquery-events


    【解决方案1】:

    这真的很烦人。我最终使用的是这个:

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

    <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>
    

    接下来,编写一个事件处理程序,通过“激活”单击的按钮和“停用”所有其他按钮来模拟单选按钮效果。 (编辑:集成了来自 cmets 的 Nick 的清洁版。)

    $('#selector button').click(function() {
        $(this).addClass('active').siblings().removeClass('active');
    
        // TODO: insert whatever you want to do with $(this) here
    });
    

    【讨论】:

    • 一个稍微简洁和优化(没有双重调用选择器)的版本:$(this).addClass('active').siblings().removeClass('active');
    • 这不适用于单选按钮。如果每个单选按钮做不同的事情,如何指定哪个是哪个
    • @MurhafSousli 我不确定我是否理解您的问题。如果您将代码插入我放置// TODO 的位置,您应该能够以$(this) 的形式访问新选择的单选按钮。
    • @Nick 我真的很喜欢你的解决方案,所以我决定将它整合到答案中,让它更加引人注目。希望你不要介意!
    • 改进:最好使用mousedown事件,因为mousedown时按钮颜色会发生变化(点击不完整)。
    【解决方案2】:

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

    第 1 步:使用the official example code 创建您的单选按钮组,并为容器指定一个 id:

    <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 处理程序:

    $("#myButtons :input").change(function() {
        console.log(this); // points to the clicked input button
    });
    

    Try the fiddle demo

    【讨论】:

    • 这是我同意的最佳解决方案。
    • @bonez 我添加了一个小提琴,请详细说明为什么它不适合你。
    • 在寻找解决方案时遇到了这个问题,在这种情况下,让你的小提琴寻找将console.log($(this).is(':checked')); 放入函数的检查条件并观察结果。现在单击预先选择的检查 - 它每次都返回 false。现在检查另一个按钮 - 哦,看,是的,现在再次单击同一个按钮 - 回到假。所以并不是一个理想的解决方案。
    • 在我最新的 Chrome 上,这很好用。这是我用来测试的更新小提琴:jsfiddle.net/9k8oc5pf/109。在哪个浏览器中会失败?
    • @SgtOddball 你注意到的问题在几年前得到了修复,github.com/twbs/bootstrap/pull/11376(小提琴仍在使用 3.0.0,抱歉)
    【解决方案3】:

    我会使用更改事件而不是像这样的点击:

    $('input[name="name-of-radio-group"]').change( function() {
      alert($(this).val())
    })
    

    【讨论】:

    • 想过这个问题,但根据 w3schools (w3schools.com/jsref/event_onchange.asp) 的说法,onchange 事件仅由
    • 这仅适用于 Chrome:Firefox 和其他浏览器不会触发更改事件,因为 Bootrap(至少从 3.0 开始)的工作方式。
    • 在最新的文档 (3.0) 上,Bootstrap 似乎建议对分组按钮使用 input type="checkbox":getbootstrap.com/javascript/#buttons-examples
    【解决方案4】:

    对于 Bootstrap 3,默认的单选/按钮组结构是:

    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-primary">
            <input type="radio" name="options" id="option1"> Option 1
        </label>
        <label class="btn btn-primary">
            <input type="radio" name="options" id="option2"> Option 2
        </label>
        <label class="btn btn-primary">
            <input type="radio" name="options" id="option3"> Option 3
        </label>
    </div>
    

    你可以像这样选择活跃的:

    $('.btn-primary').on('click', function(){
        alert($(this).find('input').attr('id'));
    }); 
    

    【讨论】:

    • 当输入具有value 属性时,为什么要使用id 字段作为值?
    【解决方案5】:

    不要使用 data-toggle 属性,以便您可以自己控制切换行为。所以它会避免'race-condition'

    我的代码:

    按钮组模板(用 .erb 编写,嵌入 ruby​​ 用于 ruby​​ on rails):

    <div class="btn-group" id="featuresFilter">
         <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
    </div>
    

    和javascript:

    onChangeFeatures = function(e){
            var el=e.target;
            $(el).button('toggle');
    
            var features=el.parentElement;
            var activeFeatures=$(features).find(".active");
            console.log(activeFeatures);
    }
    

    点击按钮后会触发onChangeFeatures函数。

    【讨论】:

    • 这对我有帮助...我遇到了一个问题,我的点击处理程序会在引导库更改按钮的切换状态之前关闭 - 所以我的代码总是认为按钮已切换。在更复杂的情况下自己处理切换绝对更好。
    • 从技术上讲,这种情况下没有race condition
    【解决方案6】:

    我需要对图表执行相同的操作,您可以在其中选择应显示的数据周期。

    因此我引入了 CSS 类 'btn-group-radio' 并使用了以下不显眼的 javascript one-liner:

    // application.js
    $(document).ready(function() {
      $('.btn-group-radio .btn').click(function() {
        $(this).addClass('active').siblings('.btn').removeClass('active');
      });
    });
    

    这里是 HTML:

    <!-- some arbitrary view -->
    <div class="btn-group btn-group-radio">
      <%= link_to '1W', charts_path('1W'), class: 'btn btn-default active', remote: true %>
      <%= link_to '1M', charts_path('1M'), class: 'btn btn-default', remote: true %>
      <%= link_to '3M', charts_path('3M'), class: 'btn btn-default', remote: true %>
      <%= link_to '6M', charts_path('6M'), class: 'btn btn-default', remote: true %>
      <%= link_to '1Y', charts_path('1Y'), class: 'btn btn-default', remote: true %>
      <%= link_to 'All', charts_path('all'), class: 'btn btn-default', remote: true %>
    </div>
    

    【讨论】:

      【解决方案7】:

      查看 Twitter Bootstrap 页面 (http://twitter.github.com/bootstrap/base-css.html#forms) 上单选按钮的 HTML 示例,您可以看到每个输入都有一个唯一的 ID 属性,即 optionsRadios1optionsRadios2

      为了完整起见,此处包含相关的 HTML 示例 sn-p:

      因此您可以使用 jQuery click 事件,然后使用 this 引用来查看被点击的 HTML 元素的 id。

      $('.controls').find('input').bind('click',function(event){ if($(this).attr('id')==='optionsRadios1'){ alert($(this).attr('id')); } 别的 { //... 调用其他函数 } });

      【讨论】:

        【解决方案8】:

        如果你的 html 与示例类似,那么点击事件是在标签上产生的,而不是在输入中,所以我使用下面的代码: HTML 示例:

        <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>      
        </div>
        

        事件的Javascript代码:

        $('#option1').parent().on("click", function () {
           alert("click fired"); 
        });
        

        【讨论】:

        • 感谢您发布此问题的答案!在 Stack Overflow 上不鼓励仅使用代码的答案,因为没有上下文的代码转储无法解释解决方案的工作方式或原因,这使得原始发布者(或任何未来的读者)难以理解其背后的逻辑。请编辑您的问题并包含对您的代码的解释,以便其他人可以从您的回答中受益。
        【解决方案9】:

        我搜索了很多页面:我找到了一个漂亮的解决方案。看看吧:

        git link

        <!DOCTYPE html>
        <html>
        <head>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        
        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
        
        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
        <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
        
            <script>
                $(function() {
                    $("#my_launch_today_chk").change(function() {
                        var chk = $(this).prop('checked');
                        if(chk == true){
                            console.log("On");
                        }else{
                            console.log("OFF");
                        }
                    });
                });
            </script>
        </head>
        <body >
        
        <input type="checkbox" id="my_launch_today_chk" checked data-on="Launch" data-off="OFF" data-toggle="toggle" data-size="small">
        </body>
        </html>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-24
          • 2012-10-23
          相关资源
          最近更新 更多