如果语句序列:
,我有盒装方式的脚本if($(selected).children('li').children('ul')){
selected = $(selected).children('li').children('ul');
$(selected).attr('data-level','3');
if( $(selected).children('li').children('ul') ){
selected = $(selected).children('li').children('ul');
$(selected).attr('data-level','4');
if( $(selected).children('li').children('ul') ){
selected = $(selected).children('li').children('ul');
$(selected).attr('data-level','5');
if( $(selected).children('li').children('ul') ){
selected = $(selected).children('li').children('ul');
$(selected).attr('data-level','6');
if( $(selected).children('li').children('ul') ){
selected = $(selected).children('li').children('ul');
$(selected).attr('data-level','7');
}
}
}
}
}
我只是想知道如何在一个简单的for循环中处理它。谢谢你的帮助。
答案 0 :(得分:1)
我想你想要这样的东西:
$('ul').attr('data-level', function () {
return $(this).parents('ul').length;
});

[data-level="0"] {
color: blue;
}
[data-level="1"] {
color: green;
}
[data-level="2"] {
color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>1</li>
</ul>
<ul>
<li>
<ul>
<li>2</li>
</ul>
</li>
</ul>
<ul>
<li>
<ul>
<li>
<ul>
<li>3</li>
</ul>
</li>
</ul>
</li>
</ul>
&#13;