如何在 jQuery 中获取父元素的索引

发布于 2024-09-12 04:19:06 字数 544 浏览 5 评论 0原文

我在编写 jQuery 函数时遇到一些问题,需要一些帮助。这是我想要完成的任务:

我有一个 ul 元素,有 5 个 li 子元素。在页面的其他地方,我有一个包含 5 个 div 子级的容器 div。当我单击第三个里的链接时,我想隐藏其他 div 并仅显示第三个。

目前,每次我单击其中一个 li 中的链接时,它都会返回页面上所有 li 中的 li 索引,而不是包含的 ul 中的索引。

这是我的代码:

$('.products #productNav li a:not(.active)').live('click', function() {
    var index = $(this).parent().index('li');
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});

有什么想法吗?非常感谢。
马库斯

I'm having some trouble writing a jQuery function and could use a little help. Here's what I'd like to accomplish:

I have a ul element with 5 li children. Elsewhere on the page, I have a container div with 5 div children. When I click a link in the third li, I'd like to hide the other divs and show only the third one.

Currently every time I click a link in one of the li's, it returns the index of the li within all li's on the page, not within the containing ul.

Here's my code:

$('.products #productNav li a:not(.active)').live('click', function() {
    var index = $(this).parent().index('li');
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});

Any ideas? Thanks much.
Marcus

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

裸钻 2024-09-19 04:19:06

.index('li') 更改为 .index(),以便它仅获取其相对于其同级的位置的索引号。

这是一个简化的示例: http://jsfiddle.net/cWWLM/

$('.products #productNav li a:not(.active)').live('click', function() {

          // Get index of the parent <li> relative to its siblings
    var index = $(this).parent().index();
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});

Change .index('li') to .index() so it only gets the index number of its position relative to its siblings.

Here's a simplified example: http://jsfiddle.net/cWWLM/

$('.products #productNav li a:not(.active)').live('click', function() {

          // Get index of the parent <li> relative to its siblings
    var index = $(this).parent().index();
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文