simon110529
simon110529

Reputation: 15

how to use jquery loop function to target many element with different ids

Currently, I have this code:

$(document).ready(function(){
    // #filtertab-00 replace this with your element id
    $('#filtertab-00 .box-content .es-nav .elastislide-next, #filtertab-00 .box-content     .es-nav .elastislide-prev').click(function() {
    // trigger lazy load
    $("#filtertab-00 img.lazy").each(function(i) {
        $(this).delay(150*i).fadeIn(1000, function() {
            var src = $(this).attr("data-original");
            $(this).attr('src',src);
        });
    });
});

});

and i want to use this function to target object names (id) as below:

filtertab-00
filtertab-10
filtertab-20
filtertab-30
filtertab-40
filtertab-50
filtertab-60
....
filtertab-90

Does anyone know how to use the loop function to get it work?

i just want this: when i click pre or next button after i select a tab(name varies from filtertab-00 to filtertab-90),it will activate lazyloading for images at current selected tab.

any idea is welcome!

Upvotes: 0

Views: 356

Answers (2)

anno1337
anno1337

Reputation: 127

This is solved through selector magic as filoxo described but since you want the images, here's another version involving find() to get your actual images.

$('div[id^="filtertab-"]').find("img.lazy").each(function(i) {
  $(this).delay(150*i).fadeIn(1000, function() {
    var src = $(this).attr("data-original");
    $(this).attr('src',src);
  });
});

In addition to that, check out the impressive list of jQuery selectors. They cover a lot of ground :)

Upvotes: 0

filoxo
filoxo

Reputation: 8390

Perhaps you could use jQuery's attribute-starts-with selector. You can then just select all IDs that begin with filtertab- using jQuery like this:

$('div[id^="filtertab-"]').each( //magic goes here );

Note: This method is slow because it has to search the DOM for elements with IDs that meet the criteria, but it does the job. I've never noticed an appreciable latency.

Upvotes: 1

Related Questions