-1

描述:我有如下代码。我已经用正确的索引标记了它们。我知道第一个 ul 标记是索引 0,第二个是索引 1。我知道 li 在每个 ul 中都是索引 0-5。我将这些设置为按钮,因此当您单击它们时,它会删除一个 CSS 类,然后添加另一个 CSS 类。但是由于范围,如果我单击第二个 UL 中的第一个子项(或如下标记的索引 1 UL),我无法使用 next() 或 prev( )。

问题:如果我点击 Index 0 LI(在 Index 1 UL 中)如何更改 Index 0 UL 的 Index 5 LI 和/或 Index 4 LI 的类别?

<ul> (Index 0 UL>)
<li><li> (Index 0 LI>)
<li><li> (Index 1 LI>)
<li><li> (Index 2 LI>)
<li><li> (Index 3 LI>)
<li><li> (Index 4 LI>)
<li><li> (Index 5 LI>)
</ul>
<ul> (Index 1 UL>)
<li><li> (Index 0 LI>)
<li><li> (Index 1 LI>)
<li><li> (Index 2 LI>)
<li><li> (Index 3 LI>)
<li><li> (Index 4 LI>)
<li><li> (Index 5 LI>)
</ul>
<ul> (Index 2 UL>)
<li><li> (Index 0 LI>)
<li><li> (Index 1 LI>)
<li><li> (Index 2 LI>)
<li><li> (Index 3 LI>)
<li><li> (Index 4 LI>)
<li><li> (Index 5 LI>)
</ul>

感谢您的任何帮助。

韦恩

4

2 回答 2

0

您可以使用这些插件方法:

jQuery.extend(jQuery.fn, {
    nextSiblingOrCousin: function() {
        var $next = this.next();
        if ($next.length == 0) {
            $next = this.parent().next().children(':first');
        }
        return $next;
    },

    prevSiblingOrCousin: function() {
        var $prev = this.prev();
        if ($prev.length == 0) {
            $prev = this.parent().prev().children(':last');
        }
        return $prev;
    }
});

有了这些,您可以将所有对 and 的调用.prev()更改.next().prevSiblingOrCousin()and .nextSiblingOrCousin()

jsfiddle 上的演示

注意:以前我认为你有一个<div>around each <ul>,但我发现你没有。

于 2013-03-03T05:09:54.893 回答
0

我已经想通了。看来 parent().prev() 将允许我与以前的父母交谈

parent().prev().find('li:last-child') 将允许我与最后一个孩子交谈。我在 wiki 中还读到了一个名为 nth-last-child-type (或类似)的东西,它允许我与前一个父级中的任意数量的元素交谈,从最后一个开始并倒计时。

韦恩

       if($(this).index()<2) { // Only do this if the button clicked on is indexed at 0 or 1
          if($(this).parent().index()!=0) { // Ensure we are not at the first parent index
            if(!$(this).parent().prev().find('li:last-child').hasClass('whatever')) { // Look for the correct class 
              alert("Current Index: "+$(this).parent().index());
              alert("Previous Parent Index: "+$(this).parent().prev().index());
              alert("Previous Index Last Child: "+$(this).parent().prev().find('li:last-child').index());
            }
          }
       }
于 2013-03-03T17:27:09.473 回答