Any ideas why this doesn't work?
<a href="javascript:alert($(this).text())">Alert This Text Here</a>
I am expecting it to alert "Alert This Text Here", but instead I get a jQuery error (G is undefined)
What am I missing?
Any ideas why this doesn't work?
<a href="javascript:alert($(this).text())">Alert This Text Here</a>
I am expecting it to alert "Alert This Text Here", but instead I get a jQuery error (G is undefined)
What am I missing?
I would assume that "this" has no association to the link you're clicking. It was never given association. this
doesn't derive its association from markup/syntax.
The following works:
<a href="#" onClick="alert($(this).text());">Some Text</a>
Ideally, you want to keep your scripting separate from your markup. You should do it like this:
$("a.someClass").click(function(event){
event.preventDefault();
alert($(this).text());
});
This example would require your anchor to have a class="someClass" to function.
If you use the "onclick" event handler, this
will be available to obtain the text()
.
<a id="alert">Alert This Text Here</a>
...
$(function() {
$("#alert").click(function() {
alert($(this).text());
});
});
As the above poster mentioned, the this needs to be in a selector to have context.
In jQuery $(this) refers to a jQuery object usually in the context of a loop or some other selector. So basically you want to select an object in jquery then use the $(this).
Example:
$("a").click(function(){alert($(this).text());});
This will work because the $(this) is in the context of the selected links.
I think you're getting it confused with the standard javascript "this" reference which will give you the current DOM object.
This post gives a nice explanation: http://remysharp.com/2007/04/12/jquerys-this-demystified/