将事件绑定到Bootstrap 3(button.js)按钮无线电时出现问题

Trouble with binding events to Bootstrap 3 (button.js) button radios

本文关键字:无线电 按钮 问题 js button 绑定 事件 Bootstrap      更新时间:2023-10-06

我在Twitter Bootstrap 3中使用button.js的单选按钮组件制作的分段控件中无法获得正确的值。当我将click事件绑定到在父窗体上运行$.serialize()的分段控件时,它会返回单选按钮的未检查值以及其他输入中的所有其他正确值。

我怀疑这可能与我无法将此事件直接绑定到分段控件的输入有关。当我尝试将事件直接绑定到输入时,没有得到响应,所以我将其绑定到标签。

以下是小提琴中的问题示例:https://jsfiddle.net/stevekas/9w94pL4o/

<form id="form">
    <div id="radios">
        <div class="radio">
            <label class="major-category">
                <input facet="exclusive" type="radio" name="hipsum" value="hashtag" />hashtag</label>
        </div>
        <div class="radio">
            <label class="major-category">
                <input facet="exclusive" type="radio" name="hipsum" value="farm-to-table" />farm-to-table</label>
        </div>
        <div class="radio">
            <label class="major-category">
                <input facet="exclusive" type="radio" name="hipsum" value="gastropub" />gastropub</label>
        </div>
    </div>
    <!--/ #radios -->
    <div id="segmented-control" class="btn-group btn-group-justified" data-toggle="buttons">
        <label class="btn btn-default active">
            <input type="radio" name="segmented-control" id="roof" value="roof" autocomplete="off" checked />roof</label>
        <label class="btn btn-default">
            <input type="radio" name="segmented-control" id="party" value="party" autocomplete="off" />party</label>
    </div>
    <!--/ #segmented-control -->
</form>

<script>
    $('.radio input').on('click', function () {
        var data = $('#form').serialize();
    });
    $('#segmented-control label').on('click', function () {
        var data = $('#form').serialize();
    });
</script>

这可能是因为在点击输入之前处理了对标签的点击(标签在DOM树中更高)。

您可以在使用setTimeout()处理完所有事件后立即强制调用调试,如下所示:

$('#segmented-control label').on('click', function () {
    setTimeout(function() {
        debug();
    }, 0);
});

这是因为setTimeout()将一个新事件排入队列,该事件将在所有当前挂起的事件之后运行。