选择表格行并使用Twitter Bootstrap保持突出显示

Jab*_*bda 18 css jquery twitter-bootstrap twitter-bootstrap-3

我正在使用Twitter Bootstrap表,其中可点击的行在悬停时突出显示(如果它更容易,我可以摆脱悬停功能).我希望所选行保持突出显示,直到单击另一行或重新点击它.

    $( document ).ready(function() {
        $('#myTable').on('click', 'tbody tr', function(event) {
            //  console.log("test ");                   
        });
Run Code Online (Sandbox Code Playgroud)

和桌子

<table class="table table-bordered table-hover" id="myTable">
    <tbody>
        <tr>
        <tr class='clickable-row'>
Run Code Online (Sandbox Code Playgroud)

我在JS中尝试了这段代码,但没有用

$(this).addClass('highlight').siblings().removeClass('highlight');
Run Code Online (Sandbox Code Playgroud)

Tim*_*wis 49

你很亲密..clickable-row在您的$("#myTable").on(...)活动上定位课程并使用Bootstrap的.active课程应该适合您:

HTML:

<table class="table table-bordered" id="myTable">
  <tr class="clickable-row">
    <th>Example</th>
  </tr>
   <tr class="clickable-row">
    <th>Example 2</th>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

$('#myTable').on('click', '.clickable-row', function(event) {
  $(this).addClass('active').siblings().removeClass('active');
});
Run Code Online (Sandbox Code Playgroud)

和一个Bootply示例

注意:如果你离开.table-hover你的桌子,你必须使用不同的课程.active,例如.bg-info(这将是一个蓝色的高光)

要从行中删除突出显示(即再次单击),请检查该行是否具有该类并将其删除:

$('#myTable').on('click', '.clickable-row', function(event) {
  if($(this).hasClass('active')){
    $(this).removeClass('active'); 
  } else {
    $(this).addClass('active').siblings().removeClass('active');
  }
});
Run Code Online (Sandbox Code Playgroud)

有关原始信息,请参阅@ BravoZulu的答案.


Bra*_*ulu 8

尝试:

$(".clickable-row").click(function(){
    if($(this).hasClass("highlight"))
        $(this).removeClass('highlight');
    else
        $(this).addClass('highlight').siblings().removeClass('highlight');
})
Run Code Online (Sandbox Code Playgroud)

  • 这是toggleClass很方便的地方. (2认同)