如何使用jQuery获取href值? [英] How to get href value using jQuery?

查看:123
本文介绍了如何使用jQuery获取href值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get href value using jQuery:

<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>

但它不起作用。为什么?

But it doesn't work. Why?

推荐答案

您需要

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

在jQuery点击处理程序中, object指的是单击的元素,而在您的情况下,您总是获得页面上第一个< a> 的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

这篇关于如何使用jQuery获取href值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆