2014-02-10 29 views
1

我的老闆告訴我要建立一個表格,其中的行突出顯示,例如 - 文本或編號與另一行的列上的文本或編號相同 - 二,這也將突出。突出顯示包含與JS或jQ相同信息的懸停表格行

我知道我可以給每一行一個類的值,並使任何對象具有相同的類高亮顯示,但我的老闆要求它根據某一列的文本或編號來高亮顯示。

這是我的jsFIDDLE示例。

如果您查看每行的第二列,您會發現第一行和第三行的值相同,因此如果我將鼠標懸停在第三行上,它應該與第一行一起突出顯示並反之亦然。

<table> 
    <tr> 
    <td>01/12/13</td> 
    <td>1234567</td> 
    <td>Lorem</td> 
    </tr> 
    <tr> 
    <td>02/12/13</td> 
    <td>7654321</td> 
    <td>Ipsum</td> 
    </tr> 
    <tr> 
    <td>02/01/14</td> 
    <td>1234567</td> 
    <td>Dolor</td> 
    </tr> 
</table> 

我該如何編寫一個允許在不使用類的情況下發生的腳本?

回答

3
// Mouse over event handler 
$('table').on('mouseover', 'td', function() { 
    // Store the hovered cell's text in a variable 
    var textToMatch = $(this).text(); 

    // Loop through every `td` element 
    $('td').each(function() { 
     // Pull selected `td` element's text 
     var text = $(this).text(); 

     // Compare this with initial text and add matching class if it matches 
     if (textToMatch === text) 
      $(this).parent().addClass('matching'); 
    }); 
}); 

// Mouse out event handler 
// This simply removes the matching styling 
$('table').on('mouseout', 'td', function() { 
    $('.matching').removeClass('matching'); 
}); 

JSFiddle demo

請注意,我稍微修改你的CSS補充:

tr:hover, tr.hover, tr.matching { 
    background: #E5E5E5; 
} 
0

小提琴:http://jsfiddle.net/JLubs/4/

JS:

$(document).ready(function(){ 
    $('table tr td:nth-child(2)').each(function(){    
      $index = $(this).parent().index() ; 
      var atext = $(this).html();    
      $('table tr td:nth-child(2):contains('+atext+')').not(this).parent().attr('match', $index); 
     }); 


    $('[match]').on('mouseover', function(){ 
     $matchInde = $(this).attr('match'); 
     //alert($matchInde); 
     $('table tr:eq('+parseInt($matchInde)+')').addClass('highlight'); 
    }).on('mouseout', function(){ 
     $matchInde = $(this).attr('match'); 
     $('table tr:eq('+parseInt($matchInde)+')').removeClass('highlight'); 
    }); 

}); 
相關問題