zedkineece
zedkineece

Reputation: 105

JQuery iterating through a loop on click

I have tried several ways to loop through a set of 4 li elements, each with a class of "item_n" where in is an integer 1-4. I need to increment by 1 with each click. I have come close, but it ended up getting worse. Here is my semi-working code:

$('input.compare').change(function(){
    var me = $(this).attr("refid");
    $('li.item_1').append('<img src="images/submenu/' + me + '.png" alt="compare1" height="28" width="28" />');
});

I need to loop through the li.item_1 selector like $('li.item_"+i"') with each click until four is reached.

Thanks in advance.

Upvotes: 0

Views: 58

Answers (2)

Wilfredo P
Wilfredo P

Reputation: 4076

I think you could try:

$('input.compare').change(function(){
    var me = $(this).attr("refid");
    $('li [class^=item_]').each(function(){
         var me = $(this).name();
         $(this).append('<img src="images/submenu/' + me + '.png" alt="compare1" height="28" width="28" />');
        });
});

where [class^=item_] will get any class that li has and start with item_

Upvotes: 1

Jane S
Jane S

Reputation: 1487

Something like this will allow you to enumerate if you give them all the same class.

$('input.compare').change(function(){
   $(".itemclass").each(function(){
     // do what you need
     alert($(this).name())
   });
 });

Upvotes: 0

Related Questions