[英]Adding a class to an ul that has more (or) less than 2 li's
I'm trying to add a class to every ul that has more (or equal&less than) 2 li's. 我正在尝试为每个具有2个以上li(或小于2个li)的ul添加一个类。
Somehow I can't get it going. 不知何故我无法继续前进。 I either end up with a class added to all level 2 ul's or to none.
我要么以添加到所有2级ul的类结束,要么都不添加任何类。
Here's the code I'm, using: 这是我使用的代码:
$(document).ready(function() {
var countli = $('ul.level_2 li').length;
if(countli >= 3) {
$("ul.level_2").addClass("short");
}
});
What am I missing? 我想念什么?
http://jsfiddle.net/gmodesignz/20dksk4y/3/ http://jsfiddle.net/gmodesignz/20dksk4y/3/
What you are doing is you are generalizing everything. 您正在做的是将所有内容概括化。 Make it specific inside the closures.
使其在封闭内特定。 See the below snippet:
请参见以下代码段:
$(document).ready(function() { $('ul.level_2').each(function () { if ($(this).children().length > 2) $(this).addClass("short"); }); });
* {font-family: 'Segoe UI';} ul {color: blue;} .short {color: red;} .large {color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <ul> <li>No Submenu</li> <li class="sub"> Long Submenu <ul class="level_2"> <li>Something</li> <li>Something</li> <li>Something</li> <li>Something</li> <li>Something</li> </ul> </li> <li class="sub"> Short Submenu <ul class="level_2"> <li>Something</li> <li>Something</li> </ul> </li> </ul>
Also you must apply the class to the parents and not the children. 另外,您必须将课程应用于父母而不是孩子。
You can add the class to ul
elements which has a 3rd li
child(ie has more than 2 li
) like 您可以将类添加到具有第三个
li
子元素(即,具有2个以上li
)的ul
元素中,例如
$(document).ready(function() { $('ul.level_2').has('li:eq(2)').addClass("short"); });
ul { color: blue; } .short { color: red; } .large { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>No Submenu</li> <li class="sub"> Long Submenu <ul class="level_2"> <li>Something</li> <li>Something</li> <li>Something</li> <li>Something</li> <li>Something</li> </ul> </li> <li class="sub"> Short Submenu <ul class="level_2"> <li>Something</li> <li>Something</li> </ul> </li> </ul>
$(document).ready(function() {
$("ul .level_2").each(function(){
var countLi = $(this).find("li").length;
if(countLi <= 3 ){
$(this).find("li").addClass("short");
}
});
});
http://jsfiddle.net/OsamaMohamed/wsu8xwwg/ http://jsfiddle.net/OsamaMohamed/wsu8xwwg/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.