【问题标题】:Highlight table rows on hover containing same info with JS or jQ悬停时突出显示包含与 JS 或 jQ 相同信息的表行
【发布时间】:2015-11-17 07:21:37
【问题描述】:

我的老板告诉我要建立一个表格,其中的行会突出显示,例如,如果文本或数字与另一行第二列的文本或数字相同,也会突出显示。

我知道我可以为每一行赋予一个类值,并使任何具有相同类的对象突出显示,但我的老板要求它根据特定列的文本或编号突出显示。

这是我的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>

我如何编写一个脚本来允许这种情况发生而不使用类?

【问题讨论】:

    标签: javascript jquery rows highlight


    【解决方案1】:
    // 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;
    }
    

    【讨论】:

      【解决方案2】:

      小提琴: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');
          });
      
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-07
        • 2012-05-13
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多