两个不同的html表突出显示相同的行顺序

时间:2013-06-25 08:06:13

标签: javascript css html-table

我有一个问题,我试图用html表进行一些操作。我有两张桌子, 当我从第一个表中悬停第一行时,它应突出显示两个表中的两行。

我已经找到了一个解决方案,用于实现这个简单的功能:

<script type="text/javascript">
function matchrow(){
document.getElementById('row1').style.backgroundColor='#f5f5f5'; 
}
function unmatchrow(){
document.getElementById('row1').style.backgroundColor='white';
}        
</script>    

在第一张桌子上我有:

<tr onmouseover="matchrow()" onmouseout="dismatchrow()" >

在第二张桌子上我有:

<tr id="row1" >

因此,当我将鼠标移到第一个表的第一行时,第二个表中的第一行突出显示。

我的问题是,如何为每一行制作它,特别是如果它将是动态表。 希望我很清楚。

3 个答案:

答案 0 :(得分:2)

我用jQuery实现了这个。它不使用突出的JS,也不需要行的其他ID。 此外,CSS类比内联样式更可取。

HTML:

<table id="t1">
    <tr><td>......</td></tr>
    <tr><td>......</td></tr>
</table>
<br/>
<table id="t2">
    <tr><td>......</td></tr>
    <tr><td>......</td></tr>
</table>

CSS:

tr.active > td
{
    background-color:#f00;
}

JS:

$(function(){
    $("#t1 tr").hover(
        function(){
            $(this).addClass('active');
            $('#t2 tr:eq(' + $('#t1 tr').index($(this)) + ')').addClass('active');
        },
        function(){
            $(this).removeClass('active');
            $('#t2 tr:eq(' + $('#t1 tr').index($(this)) + ')').removeClass('active');
        }
    );
});

这是现场小提琴:http://jsfiddle.net/keaukraine/KBEhA/1/

答案 1 :(得分:1)

您可以将div id用作函数

中的参数
 <tr onmouseover="matchrow('row1')" onmouseout="dismatchrow('row1')">

 function matchrow(divid){
      document.getElementById(divid).style.backgroundcolor='#F5F5F5';
 }
 function dismatchrow(divid){
      document.getElementById(divid).style.backgroundcolor='white';
 }

答案 2 :(得分:0)

你可以使用jQuery。

使用.eq().index()功能。

一种方法:

HTML:

<table border="1">
    <tr>
        <td>Row1</td>
    </tr>
    <tr>
        <td>Row2</td>
    </tr>
    <tr>
        <td>Row3</td>
    </tr>
    <tr>
        <td>Row4</td>
    </tr>
</table>

<table border="1">
    <tr>
        <td>Row1</td>
    </tr>
    <tr>
        <td>Row2</td>
    </tr>
    <tr>
        <td>Row3</td>
    </tr>    
</table>

JS:

$('table tr').hover(function()
{
    var index = $(this).index();
    $('table').each(function()
    {
        $(this).find('tr').eq(index).css('color', 'red');
    });
});

可以找到一个工作示例here