jQuery 找到它的父母的父母和第一个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18531265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find parent and first child of it's parent
提问by pashata
I am trying to find the parent of an element and it's parent first child, the code is like this:
我试图找到一个元素的父元素,它是父元素的第一个子元素,代码是这样的:
<ul class="lowerMenu">
<li><a href="" class="selected">Welcome</a></li>
<li><a href="">Logo</a></li>
<li><a href="">Websites</a></li>
<li><a href="">Stationery</a></li>
<li><a href="">Illustration</a></li>
<li><a href="">Full Pack</a></li>
</ul>
function setIntervalAndExecute() {
changeImages();
setTimeout(function(){
showImages(imagesArray);
},500);
var intervalot = window.setInterval(function(){
changeImages();
var selected = $('.selected');
if (!selected.parent().is(':last-child')) {
$('.selected').parent().next().children().addClass('selected');
selected.removeClass('selected');
} else {
$('.selected').parent().parent().children(':first-child').addClass('selected');
selected.removeClass('selected'); // nesho ne mi rabotit ovdeki
}
window.setTimeout(function(){
showImages(imagesArray);
},500);
},10000);
return intervalot;
}
var intervalot = setIntervalAndExecute();
I know it's a little complicated but i'm new to jquery , so what i'm trying to do is after the class 'selected' gets to the last element i want to remove it and set it to the first element. I've tried with this but it doesn't seem to be working
我知道这有点复杂,但我是 jquery 的新手,所以我想要做的是在“selected”类到达最后一个元素后,我想将其删除并将其设置为第一个元素。我试过这个,但它似乎不起作用
$('.selected').parent().parent().children(':first-child').addClass('selected');
and when it gets to the last element the interval is executing twice and then stops. This is the site that i'm working on:
当它到达最后一个元素时,间隔执行两次然后停止。这是我正在处理的网站:
回答by Barmar
If you go up two levels, then find the next child, you're only going down one level -- you're setting the selected
class on the <li>
, not the <a>
below it.. You need to go down another level. So it should be:
如果你上两层,然后找到下一个孩子,你只会下一层——你把selected
班级设置在上<li>
,而不是<a>
下面.. 你需要下一层。所以应该是:
$('.selected').parent().parent().children(':first-child').children().addClass('selected');
Another way to get there is:
到达那里的另一种方法是:
$('.selected').parent().siblings(':first-child').children().addClass('selected');
回答by RONE
回答by Rituraj ratan
回答by Sai Chaithanya
There is no need of total traversing back to the parent one after the other in a hierarchy, you can just do use parents()
instead of parent()
in this way
不需要在层次结构中一个接一个地完全遍历回父级,您可以使用parents()
而不是parent()
这种方式
$('.selected').parents('ul.lowerMenu').children(:first-child').addClass('selected');
Try it this is working!!
试试看,这是有效的!!