【问题标题】:When using jquery's next() function to get the next element in a list, how do I get the first element after reaching the end of the list?使用 jquery 的 next() 函数获取列表中的下一个元素时,如何在到达列表末尾后获取第一个元素?
【发布时间】:2012-07-10 01:09:50
【问题描述】:

从技术上讲,这不是针对“列表”(ul -> li),而是针对容器 div 内的一系列 div 块。我尝试了许多不同的方法来尝试实现这一目标,但它们都不起作用。发生的情况是,当我到达最后一个元素,然后单击“下一步”按钮时,它会将我带到列表中的第二个元素,而不是第一个元素。这通常是我正在使用的代码:

<div class="wrapperClass">
<div class="myClass" id="ID1">
    <div class="anotherClass">
        <input value="myValue1"/>
    </div>
</div>
<div class="myClass" id="ID2">
    <div class="anotherClass">
        <input value="myValue2"/>
    </div>
</div>
<div class="myClass" id="ID3">
    <div class="anotherClass"">
        <input value="myValue3"/>
    </div>
</div>
...
</div>

var nextID = $('div#'+ID).next().find('input').val();
var lastID = $('div#'+ID+':last').find('input').val();

if( nextID == lastID )
{
    nextID = $('.wrapperClass').find('input:first').val();
}
// other code

【问题讨论】:

  • 我见过最长的标题!
  • $('div#'+ID+':last') 没有意义 id 是唯一的,不应该有最后一个元素。你可以试试$('.myClass:last')
  • 我同意!我刚刚编辑了代码,我忘了添加“包装器”div。我的 jquery 函数接收一个名为“ID”的参数。我尝试了很多不同的东西,比如使用 `$('.myClass:first').find('input').val() 等。它总是让我回到第二个元素。
  • 发布的代码在这里工作:jsfiddle.net/RNrg2

标签: jquery next


【解决方案1】:

我意识到我的错误。我应该写的

if( currentID == lastID )
{
    // blah
}

我也写错了

$('div#'+ID+':last')

因为 id 必须是唯一的。感谢“未定义”(指出这一点的未透露姓名的人)。我显然是个新手。

【讨论】:

    猜你喜欢
    • 2015-02-10
    • 2016-12-31
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2012-08-21
    • 2020-07-31
    • 2011-12-31
    • 1970-01-01
    相关资源
    最近更新 更多