我有一张看起来像这样的桌子。
<table>
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody>
<tr class="data">
<td>Info here</th>
<td><a href"/url_here" class="edit">Edit</a></td>
</tr>
<tr class="data">
<td>More here</th>
<td><a href"/url_here" class="edit">Edit</a></td>
</tr>
</tbody>
</table>
我想当您将鼠标悬停在 .txt 文件内的任何行上时显示“编辑”链接。我尝试了几种方法来做到这一点,但仍然遇到同样的问题。假设我只是以错误的方式思考这个问题。
这就是我目前所拥有的。
$('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");
})
现有代码的问题是,除非您直接将鼠标悬停在编辑链接上,否则它不会添加所选的类。就像我上面提到的那样,当您将鼠标悬停在该行中的任何位置时,我需要它来添加所选的类。我也只希望它显示该特定行的编辑链接。
任何帮助我都会非常感激,因为我把头发拉了几个小时,我知道这可能是愚蠢的事情。谢谢!
一些东西:
- 你传递给魔法的字符串
$()
如果您想要设置特定元素的样式,则 jQuery 函数可以等效于您在 CSS 样式表中放入的函数。您现在使用选择器的方式除了不是很清楚之外效率非常低。例如,使用=*
选择器正在尝试查找包含该字符串的所有链接edit
anywhere在类属性中。所以与一类链接abceditabc
会匹配的。这使得 jQuery 需要做更多的工作来查找这些不存在的链接。可接受的用法是使用选择器字符串,例如a.edit
其中jQuery可以快速判断它是什么以及如何获取它。
- 每当你像现在这样进行事件绑定时,
this
指的是函数内当前正在作用事件的元素。除非您正在进行事件委托,否则您不会真正使用e.target
.
- 您的代码仅在将鼠标悬停在链接直接上方时才起作用的原因是,每当您将鼠标悬停在不同的单元格上时
e.target
将是一个兄弟姐妹。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();
});
});
您可以看到该代码作用于您发布的 HTMLhere http://jsbin.com/iguro。在 FF、IE 上为我工作。
还有一些进一步的建议:
- 总是有jQuery 文档 http://docs.jquery.com/Main_Page打开。它非常擅长解释事物是如何运作的。
- 习惯使用 Firefox/Firebug http://getfirebug.com/调试 jQuery 时。使用
console.log(this);
当您想要准确查看选择的内容时,在选择器中是一项不可低估的功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)