开发者

Pulling and placing a href with jQuery

I'm trying to pull the a href from a dynamic link and i开发者_如何转开发nserting the a href src into another link.

An extract from my HTML code:

<li id="source_ahref"><a href="http://www.sitepoint.com/forums/showthread.php?p=4729682#post4729682">This is the Source Link</a></li>
<li class="text">Support Document 4&nbsp;<a id="target_ahref" href="#">Read Document</a></li>

My Javascript code:

<script type="text/javascript">
  var theHref = $("#source_ahref a:first").attr("href");
  $("#target_ahref a:first").attr("href", theHref);
</script>

You can see my complete code at http://jsfiddle.net/prodac/Azr7K/

Thank you! :)


Small correction,

<script type="text/javascript">
  var theHref = $("#source_ahref a:first").attr("href");
  $("#target_ahref").attr("href", theHref);
</script>

#target_ahref is sufficient as it is id of anchor tag

Assuming your id is your class [as per below comments], here is updated code

<script type="text/javascript">
     $.each($(".source_ahref"),function(){
         var theHref = $("a:first",$(this)).attr("href");
         $(".target_ahref",$(this).parent()).attr("href", theHref);
     });
</script>


Chinmayee's answer, following the update, is not correct any more. Assuming that you're HTML structure looks like that in your question, with each li element next to each other, then you can use this instead:

$('.target_ahref').attr('href', function(){
    return $(this).parent().prev().children('a').attr('href');
});

Depending on your situation, you might also want use this selector for the return statement:

return $(this).parent().prevAll('.source_ahref').first().children('a').attr('href');


Replace $("#target_ahref a:first").attr("href", theHref); with the following:

$("#target_ahref").attr("href", theHref);

Coz your #target_ahref is actually the a itself, so it is not needed to refer to the a:first.


I finally managed to put a working solution together. A big thanks to everybody! :)

The code can be viewed at http://jsfiddle.net/prodac/qvBn2/. Feel free to use and edit a!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜