2015-03-25 162 views
0

的第一个孩子。如果我有这样的穿越回到同一母公司

<ul class='halo'> <-first 
    <li>1</li> 
    <li>1</li> 
    <li class='world'>2</li> 
</ul> 
<ul class='halo'> <-second 
    <li>q</li> 
    <li>w</li> 
    <li>w</li> 
</ul> 

$(".somewhere").on("click", function() {  
    if ($("ul li:last-child").hasClass("world") { 
     $last = $("ul li:last-child"); 
     $last.removeClass("world"); 
     $last.closest("ul li:first-child").addClass("world"); 
    } 
}); 

我有一个上点击事件触发其确定李是父的最后一个孩子的列表。但由于jquery没有“最远”的功能......只有最接近的。

所以,如果它的ul的最后一个孩子,我想选择ul li:第一个孩子没有提到第二个ul。我不知道为什么,但$(this)不工作/指的是当前节点。

如何遍历该父项中最远的li?

+0

显示您的jQuery代码。 '$(this).closest('ul')'为你工作。 – Satpal 2015-03-25 07:20:07

+0

只是'$(this).closest('ul.halo')' – 2015-03-25 07:20:49

+0

@ArunPJohny因为不知道什么原因,$(this)不工作,因为我认为是因为我没有发射一个事件,否则我无法解释... – Andrew 2015-03-25 07:22:27

回答

0

如果我正确理解你,这样的事情应该工作:

$('#someOtherElement').click(function() { 
 
    var li = $('#container').find('li.world'); // cache the currently selected li 
 
    var lis = li.parent().find('li'); // get all the lis in this ul 
 
    lis.removeClass('world'); 
 
    li.addClass('world'); // this is probably handled elsewhere in your code 
 
    var cur = lis.index(li); // get the index of the clicked li 
 
    if (cur >= lis.length - 1) { // check if is the last li in this ul 
 
    li.removeClass("world"); // if so move back to the first li in this ul 
 
    lis.eq(0).addClass("world") 
 
    }; 
 
}); 
 

 

 
// handle normal link clicks, elsewhere in your own code 
 
$('#container li').click(function() { 
 
    var li = $(this) 
 
    var lis = li.parent().find('li'); 
 
    lis.removeClass('world'); 
 
    li.addClass('world'); 
 
});
.world { 
 
    color: red; 
 
} 
 
#someOtherElement { 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: #cccccc; 
 
    padding:10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="someOtherElement"> 
 
    click in here 
 
</div> 
 
<div id="container"> 
 
    <ul class='halo'> 
 
    <li class='world'>Some text</li> 
 
    <li class=''>Some text</li> 
 
    <li class=''>Some text</li> 
 
    <li class=''>Some text</li> 
 
    </ul> 
 
    <ul class='halo'> 
 
    <li>q</li> 
 
    <li>w</li> 
 
    <li>w</li> 
 
    <li>w</li> 
 
    </ul> 
 
</div>

+0

如果点击事件不是直接在另一个div中的ul下面,我怎么能做到上述效果? – Andrew 2015-03-25 08:25:17

+0

@Andrew更新超过 – DelightedD0D 2015-03-25 08:49:03

+0

不知何故我不能得到“someotherelement”触发点击...我不明白为什么这行“lis.eq(0).addClass(”世界“)”不会引用回“一些文字“因为我的eq(0)回到第一个li ...并且忽略了所有的父... li.eq(0) – Andrew 2015-03-25 09:05:17