jQuery 查找“第 n 个子级”价值
我有一个 ul 设置为导航,我将在悬停时为其设置动画。
由于所有导航项都有不同的宽度,我将把它们的默认宽度存储在一个数组中,以便在悬停时,这些宽度可以传递回 animate 方法。
我需要一种方法来查找元素的“第 n 个子元素”,以便从数组中检索正确的宽度。
像这样:
var count = $(this).count(); //obviously this isn't right!
这样我就可以做:
$(this).animate({'width':array(count)}, 400);
任何建议都会对我有很大帮助 - 如果有更好的方法来做这种事情,我很乐意接受指点!
I have a ul set up as navigation, which I'll be animating on hover.
As all the nav items are different widths, I'll be storing their default widths in an Array, so that on hover out, these widths can be passed back in to the animate method.
What I need is a way to find what 'nth-child' the element is in order to retrieve the correct width from the array.
Something like:
var count = $(this).count(); //obviously this isn't right!
So that then I can do:
$(this).animate({'width':array(count)}, 400);
Any suggestions would help me a lot - and if there's a better way to do this kind of thing I'd gladly accept pointers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为
index
就是您要寻找的。它告诉您某个元素相对于其兄弟元素的位置,例如,父元素中的第二个元素是索引 1。您可以使用选择器,这样您就只考虑某些兄弟元素而不考虑其他元素,等等。I think
index
is what you're looking for. It tells you where an element is relative to its siblings, e.g., the second element within the parent is index 1. You can use selectors so you only consider certain siblings and not others, etc.如果您确实想存储最后的宽度,请使用
.data()
在每个东西
类似这样的
,这是一个粗略的例子,但我想它比数组更好......这样,你就可以确定每个
if you really want to store the last width, use
.data()
in each <li>something like
then something like,
this is a rough example but I guess it's better than array... in this way, you are sure each <li> is holding the right value....
像这样的html
和像这样的脚本
html like this
and script like this