[英]Jquery CSS- nested <li> 4 levels deep call the parent
Okay so I am stylizing a dynamic menu so I can't just assign class names or even just html code this. 好的,所以我正在设计一个动态菜单,所以我不能只分配类名,甚至只是分配html代码。
Here is what I am dealing with: I need to stylize each parent in something like this: 以下是我正在处理的内容:我需要将每个父项设置为这样的样式:
<div class="menu">
<ul>
<li>
Level 1
<ul>
<li>Level 2</li>
<li>Level 2
<ul>
<li>Level 3</li>
<li>Level 3</li>
<li>Level 3
<ul>
<li>Level 4</li>
<li>Level 4</li>
<li>Level 4</li>
<li>Level 4</li>
</ul>
</li>
</ul>
</li>
<li>Level 2</li>
<li>Level 2</li>
</ul>
</li>
</ul>
</div>
And I need to change all the parents with a jquery afterwards with something like: 然后我需要用jquery改变所有的父母,比如:
jQuery('.menu').find('li.parent').prepend('<i class="icon-plus"></i>');
I need to change all parents with a child menu. 我需要用子菜单改变所有父母。 How do I do that?
我怎么做? Thanks in advance
提前致谢
This should do the job, if I understand your question correctly: 如果我正确理解你的问题,这应该可以胜任:
jQuery('.menu li > ul').parent().prepend('<i class="icon-plus"></i>');
我认为这可以适用于你的情况( li:parent )。
jQuery('.menu').find('li:parent').prepend('<i style="" class="icon-plus"></i>');
I am not sure, if I understood your question correctly. 如果我理解你的问题,我不确定。
Anyway, the simplest solution to what I think your problem is, would be to iterate through each ul-element following a .menu and check whether the parent is a li-element and apply your styling: 无论如何,我认为你的问题最简单的解决方案是遍历.menu之后的每个ul元素,并检查父元素是否是li元素并应用你的样式:
jQuery('.menu').find('ul').each(function(){
if (jQuery(this).parent().is('li'))
jQuery(this).parent().prepend('<i class="icon-plus"></i>');
});
I think you'll need an if statement, something like: 我想你需要一个if语句,比如:
if ($('.menu>ul>li>ul')){
$('.menu>ul').prepend('<i class="icon-plus"></i>');
}
Might have to do one for each level, so: 可能必须为每个级别执行一个,所以:
if ($('.menu>ul>li>ul>li>ul')){
$('.menu>ul>li>ul').prepend('<i class="icon-plus"></i>');
}
// return all li elements inside of the menu class //返回菜单类中的所有li元素
$('.menu').find('li');
this will find the 4th level and each level after that. 这将找到第4级和之后的每个级别。
$('.menu').find('ul li ul li ul li ul li').each(function(index, element){
// validate that this is indeed correct
// 4th level elements and deeper
console.log(element);
// do stuff
});
Honestly its better to just use a class when constructing these html elements. 老实说,在构造这些html元素时使用类更好。 Its faster and help other people read the code.
它更快,并帮助其他人阅读代码。
I'm not sure about your requirements, but I think you are feeling difficulty in finding LI elements which contain a UL. 我不确定你的要求,但我认为你很难找到包含UL的LI元素。 The following code will help you find such elements.
以下代码将帮助您找到这些元素。
$('.menu li>ul').parent().addClass('node')
Now you can do the required operation on this. 现在,您可以对此执行所需的操作。 Please come back if further help required.
如果需要进一步的帮助,请回来。
Please mark as answer if it helped you. 如果有帮助,请标记为答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.