【问题标题】:jquery hover on table row with .live help使用.live帮助将jquery悬停在表格行上
【发布时间】:2011-07-28 04:17:13
【问题描述】:

我有一张表,我使用以下方法动态创建行:

$('#AjaxResultTable > tbody:last').append('<tr class="row"><td class="expandResult" title="Click to expand/collapse">&#43;</td>' + id + name + suburb + state + zip + '</tr>').hide().fadeIn(200);

当我将鼠标悬停在行上时,我想更改它们的背景颜色,并在我不悬停时更改回来。

我试过了

$('#AjaxResultTable tr').hover(function () {
    $(this).css('background-color', '#f5f5f5');
}, function () {
    $(this).css('background-color', '#fff');
});

但那没有用,所以我尝试了

$('#AjaxResultTable tr').live('hover', function () {
    $(this).css('background-color', '#f5f5f5');
}, function () {
    $(this).css('background-color', '#fff');
});

当我将鼠标悬停在一行上时它会改变背景颜色,但当我不在时它不会变回白色。

有什么建议吗?

提前致谢。

【问题讨论】:

    标签: jquery css


    【解决方案1】:

    我会做一个简单的事件处理程序来切换一个类。

    JS

    $('#AjaxResultTable').delegate('tr', 'mouseenter mouseleave', function() {
        $(this).toggleClass('hover');
    });
    

    CSS

    .hover {
      background-color: #F5F5F5;
    }
    

    编辑:在您的示例中,该属性应称为backgroundColor(而不是background-color

    编辑 2: .live() 有一些注意事项,其中之一是与 .hover() 绑定。请参阅 API 文档here

    As of jQuery 1.4.1 the hover event can be specified (mapping to mouseenter and mouseleave, which, in turn, are mapped to mouseover and mouseout).
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      我建议严格使用 css。如果您的页面上发生了很多事情,尤其是使用实时处理程序,您将开始看到一些性能下降。

      像这样的 css 选择器:将更改悬停行中所有 td 的背景颜色。

      #YourTableId tbody tr:hover td
      {
          background-color:#F0F6Fc; 
      }
      

      【讨论】:

        【解决方案3】:

        是的,我也会在 Css 中更改演示样式。 有些东西活在被放在首位的地方

        #yourTableID tbody td:hover tr
        {
           backgroundColor:#F0F6Fc;
            color: #FFF;
        }
        
        or .yourTableClass tr:hover
        {
           backgroundColor:#F0F6Fc;
            color: #FFF;
        }
        

        我也认为它就在这里,但如果您使用的是 IE...7-无论我推荐使用什么 whatever:hover文件

        【讨论】:

          【解决方案4】:

          你可以使用.mouseleave() listener..看看这里:http://api.jquery.com/mouseleave/

          【讨论】:

            【解决方案5】:

            您需要将背景颜色应用于 td/th 而不是 tr。在这种情况下,最好使用基于类的系统

            $('#AjaxResultTable tr').hover(function () {
              $(this).addClass('hover');
            }, function () {
              $(this).removeClass('hover');
            });
            
            tr.hover td, tr.hover th { background-color: #f5f5f5; }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-10-09
              • 2010-11-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-03-28
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多