如果span.toggle
的父级内部没有li
元素,我想添加我的ul
。
HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>No Title</title>
</head>
<body>
<ul>
<li>
<span class="toggle"></span><input type="checkbox" name="" id="0"><label for="0">Main 1</label>
<ul>
<span class="toggle"></span> <li><input type="checkbox" name="" id="0-1"><label for="0-1">Child 1</label></li>
<span class="toggle"></span><li><input type="checkbox" name="" id="0-2"><label for="0-2">Child 2</label>
<ul>
<span class="toggle"></span> <li><input type="checkbox" name="" id="0-1-1"><label for="0-1-1">Sub Child 1</label></li>
<span class="toggle"></span><li><input type="checkbox" name="" id="0-1-2"><label for="0-1-2">Sub Child 2</label></li>
</ul>
</li>
<span class="toggle"></span> <li><input type="checkbox" name="" id="0-3"><label for="0-3">Child 3</label></li>
<span class="toggle"></span> <li><input type="checkbox" name="" id="0-4"><label for="0-4">Child 4</label></li>
</ul>
</li>
<li>
<span class="toggle"></span> <input type="checkbox" name="" id="1"><label for="1">Main 2</label>
</li>
<li>
<span class="toggle"></span> <input type="checkbox" name="" id="2"><label for="2">Main 2</label>
<ul>
<li>
<span class="toggle"></span> <input type="checkbox" name="" id="2-1"><label for="2-1">Child 1</label>
</li>
</ul>
</li>
</ul>
<script type="text/javascript" src="https://cdn.anitur.com.tr/js/jquery-1.8.2.min.js" ></script>
</body>
</html>
CSS:
ul{
list-style: none;
padding:0;
margin: 0;
margin-left:20px;
font:13px calibri;
}
input[type="checkbox"]{
vertical-align:middle;
}
span.toggle{
float:left;
display:block;
background:url("https://cdn3.iconfinder.com/data/icons/fatcow/16/bullet_toggle_plus.png") no-repeat 0px 1px;
width:16px;
height:16px;
}
ul> * ul {
display:none;
}
input[type="checkbox"]:checked ~ ul{
display:block;
}
jQuery的:
$(function(){
$("ul li").children("ul").each(function(){
$(this).find("li").addClass("parentUl");
});
});
答案 0 :(得分:0)
查看Get all elements without child node in jQuery
$('li'):not(:has(*)).addClass('classy');
答案 1 :(得分:0)
$('ul > li').each(function(i,t){
var t = $(t);
if(! t.children('ul').length){
t.children('span').addClass('add-class');
}
});