如何使用jQuery获取href值?

Adi*_*ing 142 javascript jquery

我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

但它不起作用.为什么?

Gar*_*eth 321

你需要

var href = $(this).attr('href');
Run Code Online (Sandbox Code Playgroud)

在jQuery单击处理程序中,this对象引用单击的元素,而在您的情况下,您总是获取<a>页面上第一个的href .顺便说一句,这就是为什么你的例子有效,但你的真实代码没有


Pri*_*tel 10

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

$(this).attr("href");
Run Code Online (Sandbox Code Playgroud)

按ID获取href值

$("#mylink").attr("href");
Run Code Online (Sandbox Code Playgroud)


小智 6

值得一提的是

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always
Run Code Online (Sandbox Code Playgroud)


小智 5

假设你有这个 html :

   <a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
Run Code Online (Sandbox Code Playgroud)

您可以使用以下 JS 片段获取并显示 href 属性:

<script>
    $(".linkClass").click(function() {
        alert($(this).attr("href"));
    });
</script>
Run Code Online (Sandbox Code Playgroud)