如何遍历div类中的对象?

时间:2011-03-24 11:26:41

标签: javascript jquery

我已经坚持了几天这个问题了,这真让我很沮丧。我正在编写我认为应该是div中的简单无限图像交换,然后将该特定div称为一个类,以便我可以在同一页面上多次使用它。这是我在下面使用的代码:

HTML:

<div class="project">
<div class="project_images">
  <img src="../images/portfolio/placeholder.jpg" />
  <img src="../images/portfolio/placeholder2.jpg" />
  <img src="../images/portfolio/placeholder3.jpg" />
  <img src="../images/portfolio/placeholder4.jpg" />
</div>
<div class="project_buttons">
  <a href="#" class="prev">PREV</a>
  <a href="#" class="next">NEXT</a>
</div>
</div>
<div class="project">
<div class="project_images">
  <img src="../images/portfolio/placeholder.jpg" />
  <img src="../images/portfolio/placeholder2.jpg" />
  <img src="../images/portfolio/placeholder3.jpg" />
  <img src="../images/portfolio/placeholder4.jpg" />
</div>
<div class="project_buttons">
  <a href="#" class="prev">PREV</a>
  <a href="#" class="next">NEXT</a>
</div>
</div>

和jQuery:

$(document).ready(function(){
  next = function(){
    var thisFirst = $(this).parents('div').prev('.project_images img:first');
    var thisLast = $(this).parents('div').prev('.project_images img:last');

    thisLast.after(thisFirst);
  }

  prev = function(){
    var thisFirst = $(this).parent('div').prev('.project_images img:first');
    var thisLast = $(this).parent('div').prev('.project_images img:last');

    thisFirst.before(thisLast);
  }

  $('.prev').click(function(){
    prev();
  });

  $('.next').click(function(){
    next();
  });
});

单击第一个div类中的“NEXT”按钮时,图像将放入同名的第二个div类(“project_images”)。我理解它为什么这样做(:first:last选择器),但我无法找到更好的方法来选择对象和/或只选择一个“project_images”类的实例。
任何帮助将不胜感激......

1 个答案:

答案 0 :(得分:0)

$(document).ready(function(){
  next = function(){
    var thisFirst = $(this).parents('.project').find('.project_images img:first');
    var thisLast = $(this).parents('.project').find('.project_images img:last');

    thisLast.after(thisFirst);
  }

  prev = function(){
    var thisFirst = $(this).parents('.project').find('.project_images img:first');
    var thisLast = $(this).parents('.project').find('.project_images img:last');

    thisFirst.before(thisLast);
  }

  $('.prev').click(prev);

  $('.next').click(next);
});