开发者

jquery - take a set of hrefs from a list and apply those hrefs to another list in order

So for example, I have a list and I need to extract the hrefs from it:

<ul class="list1">
<li><a href="link1">Link1</a></li>
<li><a href="link2">Link2</a></li>
<li><a href="link3">Link3</a></li>
</ul>

BTW, this forums spam protection is not letting me put any more hyper links which is why the code above is semantically incorrect.

And apply those hrefs to the list below in order

<ul class="list2">
<li><a>Link1</a></li>
<li><a>Link2</a></li>
<li><a>Link3</a></li>
</ul>

It is to be dynamic (meaning as many hrefs in the first list as I want), so I'm not looking to use eq or nth, I've gotten this far by reading help in this forum, but am unclear on how to continue with applying the hrefs to the second list:

var hrefs = '';

$('ul#direction-fade-slider li a.url').each(function(idx, item) {  
  hrefs += item.href + '\n';  
});

Any help would be greatly appreciated开发者_开发知识库! Thanks!


You can do it using a .each() loop like this:

var anchors = $("ul.list2 a");
$("ul.list1 a").each(function(i) {
   anchors.get(i).href = this.href;
});

All this is doing it getting the destination anchors (or you can reverse it...), looping through the <a> elements in order and setting the href on the corresponding one at the same index in the destination .list2.

Alternatively, you could use .attr() like this:

var source = $("ul.list1 a");
$("ul.list2 a").attr('href', function(i) {
   return source.eq(i).attr('href');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜