简体   繁体   中英

Targeting a particular div using jQuery

I have this in my HTML:

<div id="slideshow">
    <div class="image">
            <img src="http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png" alt="Bart"/>
            <div class="caption">Bart Simpson</div>
    </div>
    <div class="image">
            <img src="http://upload.wikimedia.org/wikipedia/en/e/ec/Lisa_Simpson.png" alt="Lisa"/>
            <div class="caption">Lisa Simpson</div>
    </div>
    <div class="image">
            <img src="http://upload.wikimedia.org/wikipedia/en/0/02/Homer_Simpson_2006.png" alt="Homer"/>
            <div class="caption">Homer Simpson</div>
        </div>
    </div>

In my Jquery, I add a class with some text into the class image. However, using:

$(".image").append(data[index]);

where data is an array containing the new class code, the code goes into all instances of the class image. Now, what I want to do is: based on the index, I want to the add the new code into a particular image class. So for index 0, I want to add the code to the class with Bart, for index 1, to the class with Lisa and so on...

I can't use if statements since the number of images in the HTML might change but not the js file.

You can use jquery's .eq() function to select elements based on their index.

$('.image').eq(index).append(data[index]);

I'm guessing you want something like this.

You can pass a function to .append() :

$(".image").append(function(index) {
    return data[index];
});

Such functions are passed the element index as the first parameter. (The current HTML contents are passed as a string as the second argument, but my example doesn't need that.)

The each function will run the function for every element that matches the selection, in this case .image . Each time the each() function is run, the index is passed to the var index . So this:

$(".image").each(function (index, element) {
  $(element).append(data[index]);
});

Will append the correct data to the div .

If you want for a div with class 'image' at a particular index you can do :

$('.image')[index].append(data[index])

or

$('.image').eq(index).append(data[index]);

If you want to do it for all divs with image classes you have to use a loop

in that case

$('.image').each(function(index,current)){
    $(current).append(data[index]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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