2

i have this code

$(document).ready(function () {
    $('a').click(function(e) {
        e.preventDefault();
        url = $(this).attr('href');
        $("body").load(href);
    });
});

But it does not work. Nothing loads. The only thing that works is e.preventdefault()

Am I doing something wrong?

4
  • how about putting the e.preventDefault() after the "load"? Also, do you see anything happening on the server where "href" is pointing? Commented Apr 19, 2011 at 16:52
  • Why would you do this with XmlHttpRequest? a elements already do this properly. Commented Apr 19, 2011 at 16:56
  • @ElGuapo: Where does href point? It's an undefined variable. :) Commented Apr 19, 2011 at 16:57
  • I assumed (probably poorly) that there was an actual <a href=""> somewhere that wasn't mentioned. Commented Apr 19, 2011 at 17:02

3 Answers 3

6
$("body").load(href);

Should be:

$("body").load(url);

Or you could do away with the variable completely:

$("body").load(this.href);
Sign up to request clarification or add additional context in comments.

1 Comment

$("body").load(this.href); is the cleanest way!
0

You have assigned href attr to variable called url, then tried to use href as a variable.

Not good:

url = $(this).attr('href');    
$("body").load(href);

Good:

url = $(this).attr('href');    
$("body").load(url);

Comments

0

You are missing the $ before the (this).attr('href'); and also use the value url for your load function call.

$(document).ready(function () {
    $('a').click(function(e) {
            e.preventDefault();
            url = $(this).attr('href');
            $("body").load(url);
    });
});

1 Comment

You could just use this.href rather than $(this).attr('href') to save on creating another jQuery object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.