循环遍历元素,直到在jQuery中找到匹配

时间:2011-12-08 00:02:32

标签: javascript jquery loops

我有一系列li项,需要最有效的方法来循环它们并返回索引。我需要交叉检查li的类,如果它有某个类,则不返回索引。

这基本上适用于具有键盘支持的应用程序式菜单。基本上,请考虑以下标记:

<ul>
    <li class="selected">First Item</li>
    <li class="disabled">Second Item</li>
    <li class="separator">Third Item</li>
    <li>Fourth Item</li>
</ul>

我想要一个可用于遍历li元素的函数,并返回下一个索引(selected的类将应用于下一个可选项)。目前,我正在循环并简单地检查li是否有separator类,如果是,则递增索引并将其返回。

但是,在上面的示例中,该函数应返回3,因为无法选择任何类disabledseparator的项目。

有人可以就如何使用jQuery实现这一点提出一些建议吗?我以为可能会做这样的事情:

function get_next_index()
{
    var current_index = $('ul li.selected');
    var index = $('ul li:gt(' + current_index + ')').not('.disabled').not('.separator').get(0).index();
    if(!index || index < current_index)
    {
        return -1;
    }
    else
    {
        return index;
    }
}

3 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

alert($("li:not(.disabled,.separator)").index());

你可以在这里看到它:

http://jsfiddle.net/Zf9Vv/

我对你的问题有点困惑,所以如果我有什么不对的地方请告诉我。我建议您阅读index方法,看看它是否符合您的预期。

答案 1 :(得分:0)

$('li').each(function () {

  if (! $(this).hasClass('disabled'))
  {
    // code for non-disabled li goes here
  }

});

我认为这基本上就是你所要求的。不确定你的意思是“返回索引” - 你是否只想要一个没有“禁用”类的所有项目的索引数组?

答案 2 :(得分:0)

我的贡献:

$("li.selected").nextAll(":not(.disabled,.separator)").first().index();

这需要以下所有兄弟姐妹,过滤掉.disabled.separator,并返回第一个的索引。

相关问题