Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each loop - using variables

Tags:

jquery

each

I have a list of products. Each product has a title and a review link. Currently the titles link directly to the individual product page, and the review links go elsewhere.

I'd like to use a jquery each loop to cycle through each li, take the href from the title (the first link), and apply it to the review link (the second link), so they both point to the product page.

Simplified code would be as follows:

<ul>
   <li><a href="product1.html">Product 1</a><a href="review1.html">Review 1</a></li>
   <li><a href="product2.html">Product 2</a><a href="review2.html">Review 2</a></li>
   <li><a href="product3.html">Product 3</a><a href="review3.html">Review 3</a></li>
</ul>

I thought it would be something like the following:

$("li").each(function(){
   var link = $("a:eq(0)").attr('href');
   $("a:eq(1)").attr("href", link);
});

But it always uses the same variable "link".

Can someone help me out?

like image 304
Marlon Creative Avatar asked May 18 '10 21:05

Marlon Creative


People also ask

What is each() in jQuery?

jQuery Misc each() Method The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

How to break jQuery each loop?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How to array loop in jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.

Can we use foreach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.


1 Answers

I am passing this as an argument to define the context for each iteration of the each() loop. On each iteration, this refers to the element in question.

$("li").each(function(){
   var link = $("a:eq(0)", this).attr('href');
   $("a:eq(1)", this).attr("href", link);
});
like image 98
Gabe Avatar answered Oct 24 '22 23:10

Gabe