如何使用jQuery获得href值?


163

我正在尝试使用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 2010年

折腾...,对不起。问题是清除缓存
阿迪Sembiring

小提琴在这里:jsfiddle.net/LijoCheeran/t1xs4wo7
LCJ

Answers:


351

你需要

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

在jQuery click处理程序内部,this对象引用被单击的元素,而在您的情况下,始终总是<a>在页面上获得href 。顺便说一句,这就是为什么您的示例可以运行,但是您的实际代码却不能运行的原因


12

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

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

通过ID获取href值

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

2

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


Chrome可以根据您的设置抑制第二个弹出窗口,您是否在chrome中测试?如果是这样,请注释掉您的第一个警报,它将起作用。
Michael La Voie 2010年

2

如果页面上有一个<a>It Works,但是,很多<a>,必须使用var href = $(this).attr('href');


1
提供不确定的输出
VishalParkash

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.