jQuery循环/ .each函数简化代码

时间:2015-10-12 09:50:51

标签: jquery loops each

我想简化以下代码。我认为使用.each函数或循环会这样做,但我需要你的帮助。

var totalImages1 = $( '#project-1 li' ).length;
$( '#project-1 li' ).each( function( k, v ) {
  $( '.number', v ).html( String( k+1 ) + ' / ' + totalImages1 );
});

var totalImages2 = $( '#project-2 li' ).length;
$( '#project-2 li' ).each( function( k, v ) {
  $( '.number', v ).html( String( k+1 ) + ' / ' + totalImages2 );
});

var totalImages3 = $( '#project-2 li' ).length;
$( '#project-3 li' ).each( function( k, v ) {
  $( '.number', v ).html( String( k+1 ) + ' / ' + totalImages3 );
});

这是相应的html:

<div class="slider-container" id="project-1">
  <ul class="slider">
    <li>
      <img src="images/1.jpg" alt="">
      <p class="caption"><span class="number"></span> This is a caption</p>
    </li>
  </ul>
</div>


<div class="slider-container" id="project-2">
  <ul class="slider">
    <li>
      <img src="images/1.jpg" alt="">
      <p class="caption"><span class="number"></span> This is a caption</p>
    </li>
    <li>
      <img src="images/2.jpg" alt="">
      <p class="caption"><span class="number"></span> This is another caption</p>
    </li>
    <li>
      <img src="images/3.jpg" alt="">
      <p class="caption"><span class="number"></span> The third caption</p>
    </li>
    <li>
      <img src="images/3.jpg" alt="">
      <p class="caption"><span class="number"></span> The third caption</p>
    </li>
  </ul>
</div>


<div class="slider-container" id="project-3">
  <ul class="slider">
    <li>
      <img src="images/1.jpg" alt="">
      <p class="caption"><span class="number"></span> This is a caption</p>
    </li>
    <li>
      <img src="images/2.jpg" alt="">
      <p class="caption"><span class="number"></span> This is another caption</p>
    </li>
    <li>
      <img src="images/3.jpg" alt="">
      <p class="caption"><span class="number"></span> The third caption</p>
    </li>
  </ul>
</div>

2 个答案:

答案 0 :(得分:4)

您可以使用多个选择器(如

)遍历父元素
$('#project-1, #project-2, #project-3').each(function () {
    var $this = $(this),
        $lis = $this.find('li'),
        totalImages = $lis.length;
    $lis.each(function (k, v) {
        $('.number', v).html((k + 1) + ' / ' + totalImages);
    });

})

但是如果你可以为所有这3个父元素分配一个公共类,那么你可以

$('.project').each(function () {
    var $this = $(this),
        $lis = $this.find('li'),
        totalImages = $lis.length;
    $lis.each(function (k, v) {
        $('.number', v).html((k + 1) + ' / ' + totalImages);
    });

})

答案 1 :(得分:0)

Arun P Johny已正确回答。

或者,您也可以使用jQuery的starts with选择器

$('div[id^="project-"] li').each( function(){
    //your code.
});

此外,在您的特定情况下,您无需担心找到div个模式为id的{​​{1}}

您的project-*元素可以直接定位,例如,

ul