为什么.index()总是返回0 [英] Why is .index() always returning 0

查看:269
本文介绍了为什么.index()总是返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对为什么.index()在此代码中返回0感到困惑.它不应该返回在jquery对象数组中找到的位置的索引吗?

I'm confused as to why .index() is returning 0 in this code. Shouldn't it return the index of where it's found in the array of jquery objects?

<div id="nav">
       <ul><a href="#">Link 1</a></ul>
       <ul><a href="#">Link 2</a></ul>
       <ul><a href="#">Link 3</a></ul>
       <ul><a href="#">Link 4</a></ul>    
</div>
<div class="parent">
    <div class="a">
        <p>this is a</p>
    </div>   
    <div class="b">
        <p>this is b</p>
    </div>
    <div class="c">
        <p>this is c</p>
    </div>
    <div class="d">
        <p>this is d</p>
    </div>
</div>

jQuery代码

 $('#nav a').click(function() {
    console.log($(this).index());
    var $div = $('.parent > div').eq($(this).index());
    $div.show();
    $('.parent > div').not($div).hide();
});​

我必须使用$(this).index('#nav a')来获取正确的索引.

I have to use $(this).index('#nav a') to get the correct index.

http://jsfiddle.net/HpCWW/2/

推荐答案

index始终为0,因为<a>是其父级(<ul>)中的第一个子级.

index is always 0 because the <a> is the 1st child in its parent (the <ul>).

尝试获取<ul>的索引.

$(this).parent().index()

注意:您的HTML无效. <ul>的唯一有效子代是<li> s.

NOTE: Your HTML isn't valid. The only valid children of <ul>s are <li>s.

这篇关于为什么.index()总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆