BootStrap 3.X单选按钮组 - 获取当前选定按钮的OnClick触发器方法

时间:2014-08-28 19:44:43

标签: jquery css html5 twitter-bootstrap twitter-bootstrap-3

我有一个像这样的按钮组:

<div id="matchMode" class="btn-group" data-toggle="buttons">
    <label class="btn btn-default center-block">
        <input type="radio" name="matchMode" value="0">All
    </label>
    <label class="btn btn-default active center-block">
        <input type="radio" name="matchMode" value="1">Filtered
    </label>
</div>

我需要按钮可以点击,以便我可以触发一些代码,一旦点击它们就刷新数据网格。我尝试过以下方法:

$(function () {
    $("#matchMode .btn").click(function() {
        RefreshDataGrid();
    })
});

似乎可以工作但RefreshDataGrid()看起来像这样:

function RefreshDataGrid() {
    var mode = $('#matchMode > .btn.active :radio').val();
    //some code that uses the var mode to refresh a data grid.
}

我想要的是,事件处理程序似乎发生在DOM中按钮之间的active类的Bootstrap更改之前。这导致我的选择不正确,我必须至少点击两次按钮才能在数据网格中获取正确的数据。

解决此问题的正确方法是什么?我觉得它应该更简单,我让它变得非常复杂。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

试试这个:

你几乎是目标!

 $(function () {
            $("#matchMode .btn").click(function () {
                RefreshDataGrid(this);
            })
        });

        function RefreshDataGrid(data) {
            var mode = data.lastElementChild.value;
            //some code that uses the var mode to refresh a data grid.
        }

DEMO

答案 1 :(得分:0)

为什么不将事件附加到change,并按checked检查所选元素:

$(function () {
    function RefreshDataGrid() {
        var mode = $('#matchMode input:checked').val();
        alert(mode);
    }

    $("#matchMode input:radio").change(function() {
        RefreshDataGrid();
    });
});

jsFiddle Demo