简体   繁体   English

Bootstrap,如果在页面加载时选中复选框,则单击时不会取消选中复选框

[英]Bootstrap, checkbox is not uncheck when clicked if the checkbox is checked on page load

When page load, a checked box does not uncheck if clicked.页面加载时,如果单击选中的框,则不会取消选中。 I have to click it twice so that it can uncheck.我必须单击它两次才能取消选中它。 How to solve this problem?如何解决这个问题呢?

My reference code can be found here in codepen .我的参考代码可以在 codepen 中找到。

HTML HTML

<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="button-group">
                <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-cog"></span> <span class="caret"></span></button>
                <ul class="dropdown-menu">
                    <li><a href="#" class="small" data-value="option1" tabIndex="-1"><input type="checkbox" checked />&nbsp;Option 1</a></li>
                    <li><a href="#" class="small" data-value="option2" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 2</a></li>
                    <li><a href="#" class="small" data-value="option3" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 3</a></li>
                    <li><a href="#" class="small" data-value="option4" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 4</a></li>
                    <li><a href="#" class="small" data-value="option5" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 5</a></li>
                    <li><a href="#" class="small" data-value="option6" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 6</a></li>
                </ul>
            </div>
        </div>
    </div>
</div>

JS JS

var options = [];

$('.dropdown-menu a').on('click', function (event) {

    var $target = $(event.currentTarget),
        val = $target.attr('data-value'),
        $inp = $target.find('input'),
        idx;

    if ((idx = options.indexOf(val)) > -1) {
        options.splice(idx, 1);
        setTimeout(function () {
            $inp.prop('checked', false)
        }, 0);
    } else {
        options.push(val);
        setTimeout(function () {
            $inp.prop('checked', true)
        }, 0);
    }

    $(event.target).blur();

    console.log(options);
    return false;
});

When you are giving checked for option1 , you are not adding it into the options array.当您checked option1 ,您不会将其添加到options数组中。 The options array is empty at the beginning causing the double clicking issue. options数组在开始时为空,导致双击问题。

If you are going to use checked then add "option1" to the options array and it will work fine.如果您打算使用已检查,则将"option1"添加到options数组中,它会正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM