Max Hudson
Max Hudson

Reputation: 10206

$(this).attr("href") not working

For some reason, this line of code is returning undefined for $(this).attr("href")

$("a").attr("href", "javascript:page('" + $(this).attr("href") + "')");

How can I get that value?

Upvotes: 2

Views: 2603

Answers (5)

Claudio Redi
Claudio Redi

Reputation: 68400

This is an alternative approach that doesn't require Javascript on your href attribute

$('a').click( function(e) {
    e.preventDefault();
    page(this.href);
} )

Upvotes: 2

xdazz
xdazz

Reputation: 160833

You don't need inline javascript, why not do like below:

$("a").click(function(){
    page(this.href);
    return false;
});

Upvotes: 2

Esailija
Esailija

Reputation: 140210

$("a").click(function(e){
    e.preventDefault();
    page(this.href);
});

Upvotes: 9

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

If you want to do that (update all href attribute of the links on the page) you could do

$("a").each(function() {
   $(this).attr("href", "javascript:page('" + $(this).attr("href") + "')");
});

Upvotes: 1

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Try:

$("a").attr("href", function (index, oldHref) {
    return "javascript:page('" + oldHref + "')");
});

Check out the documentation for attr for information about the overload that takes a function reference.

Although as @Pointy points, out, you should consider writing an event handler instead of using javascript: inside your markup.

Upvotes: 5

Related Questions