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?
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?
Share Improve this question asked Jul 2, 2012 at 14:38 Max HudsonMax Hudson 10.2k15 gold badges60 silver badges110 bronze badges 2- 5 Linking to javascript is smelly. If it's possible, use events instead – Kos Commented Jul 2, 2012 at 14:41
- 1 Using "javascript:" URLs is kind-of ugly. Why not use a "click" handler? – Pointy Commented Jul 2, 2012 at 14:41
5 Answers
Reset to default 9$("a").click(function(e){
e.preventDefault();
page(this.href);
});
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.
You don't need inline javascript, why not do like below:
$("a").click(function(){
page(this.href);
return false;
});
This is an alternative approach that doesn't require Javascript on your href attribute
$('a').click( function(e) {
e.preventDefault();
page(this.href);
} )
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") + "')");
});