如何使用.each循环div中的元素?

时间:2016-03-10 01:35:09

标签: javascript jquery html jquery-selectors each

我试过阅读jQuery的api,但这只是我第二次使用jQuery,所以我发现自己有点迷失。

我有一个div设置,下面有一个图像列表。

<div id="slides">
    <img src="images/casting1.jpg" alt="Casting on the Upper Kings">
    <img src="images/casting2.jpg" alt="Casting on the Lower Kings">
    <img src="images/casting3.jpg" alt="Casting at another location!">
    <img src="images/catchrelease.jpg" alt="Catch and Release on the Big Horn">
    <img src="images/fish.jpg" alt="Catching on the South Fork">
    <img src="images/fish1.jpg" alt="Catching on the North Fork">
    <img src="images/lures.jpg" alt="The Lures for Catching">
</div>

所以我首先使用:

选择了div
var slides = $("#slides");

但是从那里我不知道要进入哪个方向。如何选择div内的单个项目?非常感谢任何帮助或指导!

7 个答案:

答案 0 :(得分:2)

您可以使用findcontextSelector来接收孩子。

var $slides = $("#slides");

var allImages = $slides.find('img'); or // $('img', $slides)

如果您想迭代图像,那么只需使用each循环来专门定位每个图像。

如果要选择特定图像。

    $('img', $slides).eq(1)  // Will get you the second image in the div. 

答案 1 :(得分:0)

$('#slides img').each(function(){
//code required using $(this).... to target each particular image of that iteration
})

答案 2 :(得分:0)

您有2个选项,.find().children().children('img').find('> img')相同

var slides = $("#slides");

slides.children('img').each(function (idx, elem) {
    console.info(idx, elem);
});

答案 3 :(得分:0)

像这样

slides.find("img").each(function(index, element){
    //keep in mind, element is a HTMLElement
    //not a JqueryObject, in order to manipulate
    //it with jquery use: $(element)
})

答案 4 :(得分:0)

试一试......

var slides = $("#slides > img").each(function () {});

console.log(slides);

记录所有img元素的数组

答案 5 :(得分:0)

您可以使用<img>

对每个$("#slides img").each进行迭代
$("#slides img").each(function(){
  // do something 
});

答案 6 :(得分:0)

使用您已创建的变量:

0
相关问题