gpt4 book ai didi

jquery .index() 函数返回不正确

转载 作者:行者123 更新时间:2023-12-01 06:30:36 26 4
gpt4 key购买 nike

帮助让我发疯.......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

最佳答案

读完 .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();会返回错误的结果,因为首页最后一页也包含在列表(这就是我的列表)。

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

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

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

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

关于jquery .index() 函数返回不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5565542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com