[英]Use jquery to check if there are nested ul and lis
I have the following code of nexted uls and lis. 我有以下uls和lis的代码。 I want to add a class with jquery to any li that has a ul child in it. 我想向其中具有ul子项的li添加一个带有jquery的类。 Here is a JSBIN 这是一个JSBIN
<ul class="tree" id="tree">
<li><input type="checkbox" name="account_settings" value="yes">Account Settings
<ul>
<li><input type="checkbox" name="one" value="one">AS One</li>
<li><input type="checkbox" name="two" value="two">AS Two</li>
<li><input type="checkbox" name="user_roles" value="user_roles">Users & Roles
<ul>
<li><input type="checkbox" name="user_role" value="add">Add</li>
<li><input type="checkbox" name="user_role" value="delete">Delete</li>
</ul>
</li>
</ul>
</li>
<li><input type="checkbox" name="rl_module" value="yes">RL Module</li>
<li><input type="checkbox" name="rl_module" value="yes">Accounting
<ul>
<li><input type="checkbox" name="vat" value="yes">VAT</li>
<li><input type="checkbox" name="bank_account" value="yes">Banking
<ul>
<li><input type="checkbox" name="view" value="yes">View</li>
<li><input type="checkbox" name="crud" value="yes">CRUD</li>
</ul>
</li>
</ul>
</li>
</ul>
jQuery jQuery的
$('#tree > li').each(function(){
if($(this).has('ul')){
$(this).prepend('<i class="fa fa-caret-right"></i>');
}
});
$('#tree ul').parent('li').addClass('fa fa-caret-right');
"If I find a ul inside #tree then add a class to it's li parent" “如果我在#tree中找到ul,则向其父级添加一个类”
JSBin: http://jsbin.com/kekugopi/2/edit JSBin: http : //jsbin.com/kekugopi/2/edit
If i understand your question correctly, you should replace 如果我正确理解您的问题,则应更换
$(this).prepend('<i class="fa fa-caret-right"></i>');
with 同
$(this).addClass("myAddedClass");
This should do the trick for just the first level of elemenst: 这应该只针对elemenst的第一个级别:
$('#tree > li').has('ul').prepend('<i class="fa fa-caret-right"></i>');
If you want to use the same code on all li's that have a ul as child use: 如果要在所有具有ul的li上使用相同的代码作为孩子使用:
$('#tree li').has('ul').prepend('<i class="fa fa-caret-right"></i>');
(notice the missing ">") (请注意缺少的“>”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.