jquery .index()函数返回错误

Val*_*Val 1 indexing jquery function core

帮助驱使我疯了.... .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
Run Code Online (Sandbox Code Playgroud)

实际网站

<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
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 6

通过.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>
Run Code Online (Sandbox Code Playgroud)

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

所以要解决这个问题,我必须做以下事情.

$('.sections:visible').index($('.sections'));
Run Code Online (Sandbox Code Playgroud)

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

希望这有助于别人:)