如何使用jQuery获取href属性的值?

211

我正在尝试使用jQuery获取href的值:

<html>
    <head>
        <title>Jquery Test</title>
         <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $("a").click(function(event) {
                alert("As you can see, the link no longer took you to jquery.com");
                var href = $('a').attr('href');
                alert(href);
                event.preventDefault();
            });
        });
        </script>
    </head>
    <body>
        <a href="http://jquery.com/">jQuery</a>
    </body>
</html>

但是它不起作用。为什么?


介意告诉我们到底出了什么问题?警告是空的吗?你甚至收到 2 个警告了吗?有任何 JS 错误吗?这对我来说是有效的... - Ben Rowe
抱歉,清除缓存是解决问题的方法。 - Adi Sembiring
在这里测试代码:https://jsfiddle.net/LijoCheeran/t1xs4wo7/ - LCJ
8个回答

440
你需要
var href = $(this).attr('href');

在jQuery的点击处理程序中,this对象指的是被点击的元素,而在您的情况下,您始终获取页面上第一个<a>的href。这也是为什么您的示例有效,但实际代码无效的原因。


18

您可以通过以下代码获取当前href值:

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

通过ID获取href的值

$("#mylink").attr("href");

18

值得一提的是

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always

4
假设您有以下html代码:
   <a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

您可以使用以下JS代码片段获取和显示href属性:
<script>
    $(".linkClass").click(function() {
        alert($(this).attr("href"));
    });
</script>

2

它可以工作...已在IE8(如果您从计算机测试文件,请不要忘记允许JavaScript运行)和chrome中进行了测试。


Chrome 可以根据您的设置抑制第二个弹出窗口,您是在 Chrome 中进行测试吗?如果是,请注释掉您的第一个警报,它就可以工作了。 - Michael La Voie

2

如果页面只有一个 <a>,那么它是有效的。但是,如果有多个 <a>,就需要使用 var href = $(this).attr('href');


1
给出未定义的输出。 - VishalParkash

0
如果你的HTML链接是这样的:
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

然后你可以像下面这样在jQuery中访问href(不需要在href中使用“a”)

$(".linkClass").on("click",accesshref);

function accesshref()
 {
 var url = $(".linkClass").attr("href");
 //OR
 var url = $(this).attr("href");
}

0
**Replacing  href attribut value to other** 
 
 <div class="cpt">
   <a href="/ref/ref/testone.html">testoneLink</a>
 </div>

  <div class="test" >
      <a href="/ref/ref/testtwo.html">testtwoLInk</a>
  </div>

 <!--Remove first default Link from href attribut -->
<script>
     Remove first default Link from href attribut
    $(".cpt a").removeAttr("href");
    
    Add  Link to same href attribut
    var testurl= $(".test").find("a").attr("href");
    $(".test a").attr('href', testurl);
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接