tags:

views:

83

answers:

4

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"&gt;&lt;/script&gt;
        <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/"&gt;jQuery&lt;/a&gt;
    </body>
</html>

but it doesn't work. why ???

A: 

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

AlfaTeK
Works in FF 3.5 as well
Nick Craver
Chrome can suppress the second popup depending on your settings, were you testing in chrome? If so, comment out your first alert and it will work.
Michael La Voie
A: 

What exactly do you want to do?

It works for me.

http://www.mattpotts.com/jq.html

Matt
+4  A: 

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

Gareth
A: 

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

wangtong