简体   繁体   English

如何使用.each遍历div中的元素?

[英]How to loop over elements in a div using .each?

I've tried reading over jQuery's api, but it's only about my second time employing jQuery so I've found myself a bit lost. 我已经尝试阅读jQuery的api,但这只是我第二次使用jQuery,所以我发现自己有些失落。

I've a div setup with a list of images underneath it. 我有一个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>

So I first selected the div by using: 因此,我首先使用以下命令选择了div:

var slides = $("#slides");

But from there I have no idea which direction to head in. How do I select the individual items inside of the div? 但是从那里我不知道该朝哪个方向前进。如何在div内选择单个项目? Any help or guidance is much appreciated! 任何帮助或指导深表感谢!

You can use find or contextSelector to get the children. 您可以使用findcontextSelector获取子级。

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

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

If you want to iterate over the images, then just use an each loop to target each image specifically. 如果要遍历图像,则只需使用each循环专门针对每个图像。

If you want to select a specific image. 如果要选择特定的图像。

    $('img', $slides).eq(1)  // Will get you the second image in the div. 
$('#slides img').each(function(){
//code required using $(this).... to target each particular image of that iteration
})

You have 2 choices, .find() or .children() , and .children('img') is the same as .find('> img') 你有两个选择, .find().children().children('img')是一样的.find('> img')

var slides = $("#slides");

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

like this 像这样

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)
})

Give this a shot... 试一下...

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

console.log(slides);

That logs an array of all the img elements 记录所有img元素的数组

You can iterate over each <img> using $("#slides img").each 您可以使用$("#slides img").each遍历每个<img> $("#slides img").each

$("#slides img").each(function(){
  // do something 
});

Using the variable you already created: 使用您已经创建的变量:

slides.children('img').each(function(){
  // here use this for the HTML element or $(this) for the jQuery wrapped one
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM