twitter-bootstrap 在 Bootstrap 3.0 中设置/取消设置复选框按钮的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19005928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code to set/unset checkbox buttons in Bootstrap 3.0
提问by uvesten
I've been trying to use a button group (as per the instructions at at http://getbootstrap.com/javascript/#buttons) and then to parse their values into a shifted array:
我一直在尝试使用按钮组(按照http://getbootstrap.com/javascript/#buttons 上的说明),然后将它们的值解析为一个移位数组:
Code for the btn-group
btn-group 的代码
<div class="btn-group" id="weekdays" data-toggle="buttons">
<label class="btn btn-default">
<input type="checkbox" >Mo
</label>
<label class="btn btn-default">
<input type="checkbox">Tu
</label>
<label class="btn btn-default">
<input type="checkbox">We
</label>
</div>
</div>
Code for reading the values
读取值的代码
$("#weekdays ").change(function(event){
var checkedDays = $("#weekdays :checkbox").map(function(){
return $(this).is(':checked') ? 1 : 0;
}).get(); // <----
var sun = checkedDays.pop();
checkedDays.unshift(sun);
console.log(checkedDays);
});
So far so good. (Even if I'm sure the code could be better written.)
到现在为止还挺好。(即使我确定代码可以写得更好。)
However, my problem comes when I try to setthe values of the checkboxes programatically, and get it reflected in the UI. I've sort of managed to change the values of the checkboxes using a number of methods $(this).prop('checked', true), etc, which seems to update the backing values, but it does nothing to change the appearance of the buttons.
但是,当我尝试以编程方式设置复选框的值并将其反映在 UI 中时,我的问题就出现了。我已经设法使用许多方法$(this).prop('checked', true)等更改复选框的值,这似乎更新了支持值,但它没有改变按钮的外观。
I've seen a number of solutions, but none that works with the Bootstrap 3.0 recommended way of setting up the checkbox btn-group. Does anyone have a solution?
我见过许多解决方案,但没有一个适用于 Bootstrap 3.0 推荐的设置复选框的方式btn-group。有没有人有办法解决吗?
回答by Blazemonger
If you use a DOM editor when clicking on the Bootstrap buttons, you'll see that a class activeis added to the label (not the checkbox input) when the button is clicked.
如果您在单击 Bootstrap 按钮时使用 DOM 编辑器,您将看到在单击按钮时将一个类active添加到标签(而不是复选框输入)。
To programmatically toggle the buttons, use the Bootstrap .button('toggle')method on the label:
要以编程方式切换按钮,请使用.button('toggle')标签上的Bootstrap方法:
$('#weekdays label').eq(n).button('toggle');
http://jsfiddle.net/mblase75/4NVvj/
http://jsfiddle.net/mblase75/4NVvj/
This will change both the appearance of the button and the checkedproperty of the checkbox within.
这将改变按钮的外观和checked其中复选框的属性。
回答by syd619
In a similar case what worked for me was this:
在类似的情况下,对我有用的是:
$('#checkBoxId').trigger("click");
Which does exactly what you want.
这正是你想要的。
PS. Not sure if it is the best but it worked for me back then.
附注。不确定它是否是最好的,但当时它对我有用。

