2012-09-27 46 views
4

在參考我以前的post如何切換Twitter Bootstrap的表格行背景顏色?

我的HTML

<table class="table table-bordered table-condensed table-striped"> 
    <thead> 
     <tr> 
      <th>Col 1</th> 
      <th>Col 2</th> 
      <th>Col 3</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td><strong>Data 1</strong></td> 
      <td>Data 2</td> 
      <td>Data 3</td> 
     </tr> 
     <tr> 
      <td><strong>Data 1</strong></td> 
      <td>Data 2</td> 
      <td>Data 3</td> 
     </tr> 
     <tr> 
      <td><strong>Data 1</strong></td> 
      <td>Data 2</td> 
      <td>Data 3</td> 
     </tr> 
    </tbody> 
</table> 

jQuery的

$(document).ready(function(){ 
    $('table.table-striped tr').on('click', function() { 
     $(this).find('td').css('background-color', '#ff0000'); 

     // toggleClass doesn't seem to work 

    }); 
}); 

我想通過我的點擊事件來切換排色對開的上。任何想法,如果這是可能的使用用戶定義的CSS選擇器?

+0

您是否有一個班級擺在首位? ??看起來像你在CSS中分配背景顏色right –

回答

5

你可以試試這個

CSS

.bg{background-color:#ff0000 !important;}​ 

JS

$(document).ready(function(){ 
    $('table.table-striped tbody tr').on('click', function() { 
     $(this).closest('table').find('td').removeClass('bg'); 
     $(this).find('td').addClass('bg'); 
    }); 
});​ 

DEMO

更新:用於切換

$(document).ready(function(){ 
    $('table.table-striped tbody tr').on('click', function() { 
     $(this).find('td').toggleClass('bg'); 
    }); 
});​ 

DEMO

+0

這似乎工作,但理想情況下,我需要能夠切換同一行......任何想法? – user1216398

+0

不明白切換同一行,你能解釋一下嗎? –

+0

我實際上已經使用你的示例了。我將它改爲:$(this).find('td')。toggleClass('bg');感謝您的幫助和很好的例子! – user1216398