How to get href value using jQuery?

前端 未结 6 450
慢半拍i
慢半拍i 2020-12-07 23:56

I\'m trying to get href value using jQuery:


    
        Jquery Test
         

        
相关标签:
6条回答
  • 2020-12-08 00:10

    You can get current href value by this code:

    $(this).attr("href");
    

    To get href value by ID

    $("#mylink").attr("href");
    
    0 讨论(0)
  • 2020-12-08 00:14

    It's worth mentioning that

    $('a').attr('href'); // gets the actual value
    $('a').prop('href'); // gets the full URL always
    
    0 讨论(0)
  • 2020-12-08 00:16

    if the page have one <a> It Works,but,many <a> ,have to use var href = $(this).attr('href');

    0 讨论(0)
  • 2020-12-08 00:30

    It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.

    0 讨论(0)
  • 2020-12-08 00:32

    You need

    var href = $(this).attr('href');
    

    Inside a jQuery click handler, the this object refers to the element clicked, whereas in your case you're always getting the href for the first <a> on the page. This, incidentally, is why your example works but your real code doesn't

    0 讨论(0)
  • 2020-12-08 00:36
    **Replacing  href** 
       <div class="cpt">
           <h2>
             <a href="/ref/ref/testone.html">testoneLink</a>
            </h2>
        </div>
     <h2 class="test" >
          <a href="/ref/ref/testtwo.html">testtwoLInk</a>
      </h2>
    
     <!--Remove first default Link from href attribut -->
    <script>
         Remove first default Link from href attribut
        $(".geturl a").removeAttr("href");
        
        Add  Link to same href attribut
        var testurl= $(".test").find("a").attr("href");
        $(".geturl a").attr('href', testurl);
    </script>
    
    0 讨论(0)
提交回复
热议问题