在表行鼠标hover上显示表格单元格

我有一张看起来像这样的桌子。

Foo Bar
Info here Edit
More here Edit

我想在鼠标hover在其中的任何行上时显示编辑链接。 我尝试了一些方法,但仍然遇到同样的问题。 假设我只是想错了方法。

这就是我现在拥有的。

 $('a[class*=edit]').hide(); $('tr[class*=data]').bind("mouseover", function(e) { $(e.target).closest('a[class*=edit]').addClass("selected"); $('a[class*=selected]:first').show(); }).mouseout(function() { $('a[class*=selected]').hide(); $('a[class*=edit]').removeClass("selected"); }) 

现有代码的问题是它不会添加所选类,除非您将鼠标hover在编辑链接上。 就像我上面提到的那样,当你将鼠标hover在那一行的任何地方时,我需要它来添加所选的类。 我也只希望它显示该特定行的编辑链接。

任何帮助都会非常感激我的头发拉了几个小时,我知道它可能是愚蠢的。 谢谢!

一些东西:

  • 如果要为特定元素设置样式,则传递给魔法$() jQuery函数的字符串可以等同于您在CSS样式表中放置的字符串。 你现在使用选择器的方式除了不太清楚外,效率极低。 例如,使用=*选择器尝试在类属性中的任何位置查找具有字符串edit所有链接。 因此,与一类abceditabc链接将匹配。 这使得jQuery在尝试查找这些不存在的链接时所做的工作远不必要。 接受的用法是使用选择器字符串,例如a.edit ,jQuery可以快速确定它是什么以及如何获取它。
  • 无论何时执行事件绑定,都会引用事件当前在函数内部执行的元素。 除非你正在进行事件委托,否则你真的不会使用e.target
  • 您的代码仅在hover直接位于链接上时才起作用的原因是因为无论何时将鼠标hover在不同的单元格上, e.target都将是兄弟td。 closest是没有能力然后遍历该td,到tr,到下一个td到链接。 即使它确实如此,你可能也想避免这种情况,因为它没有必要。 这与第二点有关,因为简单地查找从表行下来的链接要容易得多。

所以,记住这些事情,你可以重写你拥有的东西:

 $(function() { $('a.edit').hide(); // hide all links with a class of edit // act upon all table rows with a class of data $('tr.data').hover(function() { // at this point, 'this' is the table row that is being hovered // we can use the find function to locate the link with a class of edit // then add a class to it and show it. $(this).find('a.edit').addClass("selected").show(); }, function() { // the second argument of the hover function is what should happen // when the mouse hovers out of the table row. In this case, we want // to find the link again, remove the class, and hide it. $(this).find('a.edit').removeClass("selected").hide(); }); }); 

您可以在此处发布的HTML上看到此代码的代码。 在FF,IE上为我工作。

还有一些建议:

  • 始终打开jQuery文档 。 它很擅长解释事情的运作方式。
  • 在调试jQuery时习惯使用Firefox / Firebug 。 使用console.log(this); 当您想要查看所选内容时,您的选择器内部是一个无法低估的function。

尝试这样的事情,假设我的逻辑正确。

 $(document).ready(function() { $('a.edit').hide(); $('tr.data').hover(function() { $(this).addClass("selected").find('a.edit').show(); }, function() { $(this).removeClass("selected").find('a.edit').hide(); }); }): 

您的特定错误很可能与您使用closest树的方法有关。

更新:您的代码无法正常工作的另一个可能原因是您没有使用jquery document.readyfunction。 我用它更新了我的代码。