【问题标题】:jquery .index() function returning incorrectjquery .index() 函数返回不正确
【发布时间】:2011-04-06 11:25:10
【问题描述】:

帮我把我逼疯.... .index() 函数不会为我返回正确的索引,除非我对 index() 的整个概念有错误:)

这就是它背后的逻辑

<div class="sections">Section 1</div>
<div class="sections">Section 2</div>
<div class="sections">Section 3</div>
<div class="sections">Section 4</div>

.sections{display:none;} //css 

$('.sections:eq(1)').show();// shows sectiond 2 text
$('.sections:visible').index();// returns 2 I expected 1

实际网站

<div class="sections">Section 1</div>
var section = $('.sections:visible').index();// returns 2
console.log($('.sections:visible').length); // returns 1
console.log($('.sections').length); // returns 1 as well since there is one section
window.location.hash = 'section-'+section;// url hash is #section-2

【问题讨论】:

  • 它在 Chrome 上使用 jsfiddle.net/DsSV5 为我返回 1
  • 为我返回 1 jsfiddle.net/AbEWF/1
  • 在 jsfiddle 上和我一样。在我的实际站点上,我只有一个 .section div,但为了更好地展示它,我在这里放了多个。我不知道这两个是从哪里来的......我使用了 .length 并返回一个,这意味着没有任何其他 div 属于同一类

标签: jquery function indexing core


【解决方案1】:

在仔细阅读.index()http://api.jquery.com/index/ 之后,我发现如果您将列表指定为属性,它将解决问题。

例如

<div class="wrap">
  <div>First Page</div>
  <div class="sections">Section 1</div>
  <div class="sections">Section 2</div>
  <div class="sections">Section 3</div>
  <div class="sections">Section 4</div>
  </div>Last Page</div>
</div>

简单地使用$('.sections:visible').index(); 会返回不正确的结果为first pagelast page are also included on the list (which is what I had).

所以要解决这个问题,我必须执行以下操作。

$('.sections:visible').index($('.sections'));

换句话说,我们说的是从$('.selections')的列表中找到:visible的索引

希望这对其他人有帮助:)

【讨论】:

    【解决方案2】:

    我认为你混淆了一些东西。数组中的索引 1 表示整个集合的第二个元素。 jquery 的选择器总是返回一个数组。

    查看Visual Jquery '.eq()'

    【讨论】:

    • 大声笑我知道我们应该在这里有一个愚蠢的仪表,这样人们就知道我们的理解程度:)
    • 如果你查看 .eq() 的例子,你就会明白我的意思。所有三个示例实际上都标记了第三个元素。
    • 是的,我知道它的索引,这意味着它从 0 而不是 1 开始,因此 .index() 函数因此索引为 0 也应该在逻辑上返回 1,但它没有看到更新的问题
    • 你应该检查api.jquery.com/index 我认为因为你低估了我的脚本知识大声笑:) 顺便说一句没有冒犯但你确实有一点
    • 是的,我现在看到了。所以我必须道歉。
    【解决方案3】:
    $('.sections:visible').index($('.sections'));
    

    换句话说,我们说的是从$('.selections')的列表中找到:visible的索引

    没有参数它给出选择器的索引。有了论据,它就反过来了。由于.sections 不是.sections:visible 的一部分,它给出-1(未找到)。

    所以正确答案是:

    $('.sections').index($('.sections:visible'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多