[英]Correct way to check if ul have li element using Jquery
I am trying to check if my <ul>
has a <li>
element in Jquery, if it does then it displays a div if not it hides it. 我正在尝试检查我的
<ul>
是否在Jquery中具有<li>
元素,如果存在,则显示div,否则将其隐藏。 So far I have the following code: 到目前为止,我有以下代码:
$(document).ready(function () {
$('#div-1 .div-2').each(function (index, item) {
var colorCount = $(item).find('.item ul li').length;
$(item).attr('data', colorCount);
if (colorCount > 0 ) {
$('.colourClass').show();
}
else {
$('.colourClass').hide();
}
});
});
Is this correct or is there a stricter and better way to do it? 这是正确的还是有更严格更好的方法呢?
I'd advise you to use toggle() function to achieve your requirements. 我建议您使用toggle()函数来满足您的要求。
const $ul = $('#test'); $('#div').toggle($ul.find('li').length > 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id='test'> <li>asdas</li> </ul> <div id='div' style='display: none;'> Show if li exist! </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.