遍历回同一父母的第一个孩子

时间:2015-03-25 07:19:31

标签: jquery

如果我有这样的清单

<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");
     }
});

我有一个on click事件触发器,用于确定li是否是父项的最后一个子项。但由于jquery没有“最远”的功能....只有最接近。

所以,如果它是ul的最后一个孩子,我想选择ul li:first-child而不引用第二个ul。我不知道为什么,但$(this)不工作/引用当前节点..

如何穿越父母最远的李?

1 个答案:

答案 0 :(得分: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>