Dan*_*l O 59 javascript jquery twitter-bootstrap twitter-bootstrap-3 jquery-events
我有一个Twitter Bootstrap按钮 - 收音机和钩子onclick事件.但是如何检查触发了哪个按钮?
我的第一个想法是简单地检查类'active',但这应该创建一个竞争条件(结果取决于是否首先处理Twitter Bootstrap事件或我自己的onclick事件).
Hen*_*ger 72
这真是令人讨厌的一个.我最终使用的是:
首先,创建一组没有data-toggle
属性的简单按钮.
<div id="selector" class="btn-group">
<button type="button" class="btn active">Day</button>
<button type="button" class="btn">Week</button>
<button type="button" class="btn">Month</button>
<button type="button" class="btn">Year</button>
</div>
Run Code Online (Sandbox Code Playgroud)
接下来,编写一个事件处理程序,通过"激活"单击的按钮和"停用"所有其他按钮来模拟单选按钮效果.(编辑:评论中集成尼克的清洁版.)
$('#selector button').click(function() {
$(this).addClass('active').siblings().removeClass('active');
// TODO: insert whatever you want to do with $(this) here
});
Run Code Online (Sandbox Code Playgroud)
mar*_*out 65
我看到很多复杂的答案,而这在Bootstrap 3中非常简单:
步骤1:使用官方示例代码创建单选按钮组,并为容器指定一个ID:
<div id="myButtons" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
</label>
</div>
Run Code Online (Sandbox Code Playgroud)
第2步:使用此jQuery处理程序:
$("#myButtons :input").change(function() {
console.log(this); // points to the clicked input button
});
Run Code Online (Sandbox Code Playgroud)
nod*_*rog 20
我会使用更改事件而不是像这样的点击:
$('input[name="name-of-radio-group"]').change( function() {
alert($(this).val())
})
Run Code Online (Sandbox Code Playgroud)
对于Bootstrap 3,默认的radio/button-group结构是:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="options" id="option1"> Option 1
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3"> Option 3
</label>
</div>
Run Code Online (Sandbox Code Playgroud)
你可以选择这样的活动:
$('.btn-primary').on('click', function(){
alert($(this).find('input').attr('id'));
});
Run Code Online (Sandbox Code Playgroud)
小智 5
不要使用数据切换属性,以便您可以自己控制切换行为.所以它会避免'竞争条件'
我的代码:
按钮组模板(用.erb编写,嵌入式红宝石用于轨道上的红宝石):
<div class="btn-group" id="featuresFilter">
<% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>
Run Code Online (Sandbox Code Playgroud)
和javascript:
onChangeFeatures = function(e){
var el=e.target;
$(el).button('toggle');
var features=el.parentElement;
var activeFeatures=$(features).find(".active");
console.log(activeFeatures);
}
Run Code Online (Sandbox Code Playgroud)
单击按钮后将触发onChangeFeatures函数.
归档时间: |
|
查看次数: |
110501 次 |
最近记录: |