使用锚点使用JQuery / Bootstrap突出显示一行表

时间:2013-06-01 19:23:34

标签: jquery twitter-bootstrap anchor highlight bootstrap-typeahead

我正在使用Bootstrap(Twitter)和JQuery。我有一个包含一些数据的表,每行都有一个id。我有一个预先检查表格中的数据。当我在我的输入中选择一个数据时,我想突出显示正确的行,这就是我使用锚点的原因。但是,我不知道如何突出这一行。

这是我的JQuery代码:

$(document).ready(function() {
    $('#typeahead').change(function() {
        window.location = "#" + $(this).val();
        //highlighting the row...
    });
});

此HTML代码仅用于测试:

<a href="#row1">Row1</a>
<a href="#row2">Row2</a>

<table class="table table-hover table-bordered">
    <tr id="row1">
        <td>A</td>
        <td>B</td>
    </tr>
    <tr id="row2">
        <td>C</td>
        <td>D</td>
    </tr>
</table>

这里是typeahead的代码:

<input type="text" id="typeahead" data-provide="typeahead" placeholder="Search a name" data-items="4" data-source='[
<?php for($i = 0 ; $i < count($typeahead) ; $i++) {

if($i+1 == count($typeahead))
echo '"'.$typeahead[$i].'"';
else
echo '"'.$typeahead[$i].'",';
} 

?>]'>

这里是typeahead数组的内容:

<input type="text" id="typeahead" data-provide="typeahead" placeholder="Search a name" data-items="4" data-source='["Christophe Chantraine","Toto Tuteur","Henris Michaux","Robert Patinson","Benjamin Brégnard","Jean-Charles Terzis","Ludovic Dermience","Claude Dianga"]'>

以下是介绍我的问题的示例代码:http://jsfiddle.net/TK7QP/6/

1 个答案:

答案 0 :(得分:4)

而不是在表行上使用id属性,而是将其更改为data-name。例如:

<tr data-name="Christophe Chantraine">
    <td>A</td>
    <td>B</td>
</tr>

将此CSS添加到样式表中:

.table-hover tbody tr.selected > td {
  background-color: #f5f5f5;
}

然后将您的jQuery代码更改为:

$(document).ready(function() {
    $('#typeahead').change(function() {
        window.location = "#" + $(this).val();
        //highlighting the row...
        $('tr[data-name="' + $(this).val() + '"]').addClass('selected');
    });
});

通过数据属性查找元素比使用id要花费更长的时间,但除非你有大量的表行,否则它不会引人注意。最简单的方法是使用数据属性,因为你必须“敲击”名称才能将它们用作id,这意味着删除所有空格,特殊字符等。

----使用id属性替代回答,以便您可以链接到表格行----

为此,您需要替换名称中的空格。以下是使用PHP如何做到这一点的示例:

<table class="table table-hover table-bordered">
    <tr id="<?php echo str_replace(' ', '_', 'Christophe Chantraine');?>">
        <td>A</td>
        <td>B</td>
    </tr>
    <tr id="<?php echo str_replace(' ', '_', 'Benjamin Brégnard');?>">
        <td>C</td>
        <td>D</td>
    </tr>
</table>

当你链接到行时,你的锚点也需要有下划线:

<a href="#Christophe_Chantraine">Christophe Chantraine</a>

然后你的jQuery应该是这样的:

$(document).ready(function() {

    $('#typeahead').change(function() {
        $('tr').removeClass('selected'); // remove class from other rows
        $('#' + $(this).val().replace(' ', '_')).addClass('selected');
        window.location = "#" +  $(this).val().replace(' ', '_');
    });
});

要添加过渡效果,您可以在CSS中执行类似的操作。如果一秒太长,则更改转换的长度:

.table-hover tbody tr.selected > td {
  background-color: #f5f5f5;
    -webkit-transition: background 1s linear;
    -moz-transition: background 1s linear;
    -ms-transition: background 1s linear;
    -o-transition: background 1s linear;
    transition: background 1s linear;
}