tags:

views:

295

answers:

4

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?

+11  A: 

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.

Jonathan Sampson
return false does the same thing as event.preventDefault()
Sean Clark Hess
You're right about the href javascript protocol has no context. Try this. <a href="javascript:alert(this === window);">Try this.</a>Returns true in FF, Safari and IE. Probably Chrome too. This probably follows spec, but I didn't find anything useful with a cursory search.
Marco
+1  A: 

If you use the "onclick" event handler, this will be available to obtain the text().

spoulson
+2  A: 
<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.

Sean Clark Hess
A: 

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/

brendan