jQuery each loop - using variables

Posted by Sam on Stack Overflow See other posts from Stack Overflow or by Sam
Published on 2010-05-18T21:17:39Z Indexed on 2010/05/18 21:20 UTC
Read the original article Hit count: 245

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about each