2012-07-07 63 views
5

我有幾個按鈕。當用戶點擊任何按鈕時,我想給他一個按鈕被點擊的印象。Bootstrap - 當存在多個按鈕時的數據切換屬性

這是代碼:

<table> 
<thead> 
<tr> 
<th><button class="btn btn-danger" >Today</button></th> 
<th><button class="btn btn-danger" >Tomorrow</button></th> 
<th><button class="btn btn-danger" >DayAfterTomorrow</button></th> 
</tr> 
</thead> 
</table> 

而且這個作品時,我有一個按鈕:

<button class="btn" data-toggle="button">Today</button> 

如果用戶點擊明天,數據切換屬性仍然是今天按鈕。相反,我想在單擊另一個按鈕時禁用數據切換屬性。

回答

5

您可以使用引導程序單選按鈕的功能,以達到這樣的效果。試試這個:

<div data-toggle="buttons-radio"> 
    <button class="btn btn-danger">Today</button> 
    <button class="btn btn-danger">Tomorrow</button> 
    <button class="btn btn-danger">DayAfterTomorrow</button> 
</div> 

演示:http://jsfiddle.net/u7Lg8/

+0

偉大的。但唯一的問題是我有按鈕作爲表頭。 – Pavan 2012-07-07 13:28:42

+0

編輯的問題。對不起 – Pavan 2012-07-07 13:30:11

+1

源代碼在https://github.com/twitter/bootstrap /blob/master/js/bootstrap-button.js#L53使用data-toggle =「buttons-radio」屬性選擇與我最接近的父級,取消激活其下的所有活動鏈接,然後切換所按按鈕的活動鏈接,如果您將標題的標籤添加到標頭的中,則應該使用data-toggle =「buttons-radio」 – guigouz 2012-11-04 13:10:10

0

您需要將按鈕分組在一個div下並在該組上設置數據切換。

你可以看到它在例如頁面Twitter bootstrap buttons

<!-- Add data-toggle="buttons-checkbox" for checkbox style toggling on btn-group --> 
<div class="btn-group" data-toggle="buttons-checkbox"> 
    <button class="btn">Left</button> 
    <button class="btn">Middle</button> 
    <button class="btn">Right</button> 
</div> 
+0

沒有。不是我在找什麼。 – Pavan 2012-07-07 12:24:49

+0

當然是的。我忘了告訴你,數據切換值需要js來獲得點擊的按鈕值,請參閱@Engineer。 – maxmax 2012-07-07 12:31:42

1

嘗試這樣的:

$('.btn').click(function(){ 
    //Removing `data-toggle` from all elements 
    $('.btn').removeData('toggle'); 
    //Adding `data-toggle` on clicked element 
    $(this).data('toggle','button');   
}); 
+0

仍然是同樣的問題:( – Pavan 2012-07-07 13:22:36

+0

編輯的問題。對不起 – Pavan 2012-07-07 13:30:06

0

這裏是我想出了我的網站

 $("input[name='dispatch']").change(function(){ 
 
      
 
      $(this).parent().siblings().removeClass('active btn-primary'); 
 
      $("#WantsDispatchService").val($(this).val()); 
 
      
 
     });

 
    <div class="btn-group btn-toggle " data-toggle="buttons"> 
 
\t <label class="btn btn-default btn-sm"> 
 
\t \t <input name="dispatch" value="false" type="checkbox"> No 
 
\t </label> 
 
\t <label class="btn btn-default btn-sm"> 
 

 
\t \t <input name="dispatch" value="true" type="checkbox"> Yes 
 
\t </label> 
 
\t 
 
</div> 
 
<input type ="hidden" id="WantsDispatchService" name="WantsDispatchService" value="false"> 
 
</div>
(只有提高是不使用隱藏變量來存儲最終值的方式)

0

您可以使用$().button('toggle')通過JavaScript切換按鈕狀態。 *

對我而言;我不能使用分組按鈕,它們在視覺上彼此分離。

我檢查是否按下了其他按鈕,並使用javascript切換回來。 這裏是我的解決方案:

$('#buttonA').click(function (e) { 
    if ($('#buttonB').attr('aria-pressed') == 'true') { 
     $('#buttonB').button('toggle'); 
    } 
    e.preventDefault(); 
}); 

$('#buttonB').click(function (e) { 
    if ($('#buttonA').attr('aria-pressed') == 'true') { 
     $('#buttonA').button('toggle'); 
    } 
    e.preventDefault(); 
});