Javascript 如何获取推特引导按钮组中选定按钮的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10941606/
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
How to get the value of selected button in twitter bootstrap button group
提问by Adham
If I haev a radio button group in bootstrap like the following :
如果我在引导程序中有一个单选按钮组,如下所示:
<div class="btn-group" data-toggle="buttons-radio">
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
</div>
How can I get
/ set
the selected value ?
我如何get
/set
选择的值?
采纳答案by u283863
var num = null;
var ele = document.querySelectorAll(".btn-group > button.btn");
for(var i=0; i<ele.length; i++){
ele[i].addEventListener("click", function(){
num = +this.innerHTML;
alert("Value is " + num);
});
}
Or jQuery:
或 jQuery:
var num = null;
$(".btn-group > button.btn").on("click", function(){
num = +this.innerHTML;
alert("Value is " + num);
});
回答by Tyler Johnson
To set the active element, add the class active
to whichever button you want selected (and deselect the rest).
要设置活动元素,请将类添加active
到您想要选择的任何按钮(并取消选择其余按钮)。
$('.btn-group > .btn').removeClass('active') // Remove any existing active classes
$('.btn-group > .btn').eq(0).addClass('active') // Add the class to the nth element
To get the html/text content of the currently active button, try something like this:
要获取当前活动按钮的 html/text 内容,请尝试以下操作:
$('.btn-group > .btn.active').html()
回答by Shivek Parmar
Here is one more solution
这是另一种解决方案
alert($('.btn-group > .btn.active').text());