计算在jQuery中有多少UL拥有如此多的LI元素

时间:2017-03-31 03:55:39

标签: jquery

我有各种 UL ,我需要了解所有现有的 UL ,有多少 UL 有两个 UL ,我正在尝试用每个人做,这将是正确的方式。

$(function(){

	var count = '';
	var total = 1;
    
	$('ul li').each(function(index, el) {
			count++;
			if(count == 12) {
				total + 1;
			}
      
			count = '';
		});
    
    console.log('We found 2 UL with 2 li');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
	<li>Item</li>
  <li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

此代码,结果:我们发现2 UL和2 li。

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
<script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory BUTTON').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>
&#13;
$(function() {


  $('ul').filter(function() {

    return $(this).children('li').length == 2
  }).css("background-color", "red")

  console.log('We found 2 UL with 2 li');
});
&#13;
&#13;
&#13;

您可以使用过滤器然后返回ul长度为== 2

的ul

答案 1 :(得分:1)

  var count = 0;
  $('ul').each(function(index, item) {
  if($(this).children('li').length == 2)
  {
  count++;
  }
  });
  
  if(count > 0)
  {
  console.log('We found '+ count +' UL with 2 li');
  }
  else
  {
  console.log('no such li is found')
  }
    
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
	<li>Item</li>
  <li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>

<ul>
	<li>Item</li>
	<li>Item</li>
</ul>