我有一张看起来像这样的桌子.
<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>
Run Code Online (Sandbox Code Playgroud)
我想在鼠标悬停在其中的任何行上时显示编辑链接.我尝试了一些方法,但仍然遇到同样的问题.假设我只是想错了方法.
这就是我现在拥有的.
$('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");
})
Run Code Online (Sandbox Code Playgroud)
现有代码的问题是它不会添加所选类,除非您将鼠标悬停在编辑链接上.就像我上面提到的那样,当你将鼠标悬停在那一行的任何地方时,我需要它来添加所选的类.我也只希望它显示该特定行的编辑链接.
任何帮助都会非常感激我的头发拉了几个小时,我知道这可能是一些愚蠢的事情.谢谢!
一些东西:
$()如果要为特定元素设置样式,则传递给魔法jQuery函数的字符串可以等同于您在CSS样式表中放置的字符串.你现在使用选择器的方式除了不太清楚外,效率极低.例如,使用=*选择器试图在class属性中的edit 任何位置查找带有字符串的所有链接.因此,与一类的链接abceditabc将匹配.这使得jQuery在尝试查找这些不存在的链接时做了大量工作.接受的用法是使用选择器字符串,例如a.editjQuery可以快速确定它是什么以及如何获取它.this引用事件当前在函数内部执行的元素.除非你正在进行事件委托,否则你真的不会使用e.target.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();
});
});
Run Code Online (Sandbox Code Playgroud)
您可以在此处发布的HTML上看到此代码的代码.在FF,IE上为我工作.
还有一些建议:
console.log(this);当您想要准确查看所选内容时,在选择器内使用是一种无法低估的功能.| 归档时间: |
|
| 查看次数: |
4667 次 |
| 最近记录: |