Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't jQuery $(this).text() work inside a link?

Tags:

jquery

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?

like image 302
Justin Vincent Avatar asked Nov 30 '22 11:11

Justin Vincent


1 Answers

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.

like image 187
Sampson Avatar answered Dec 11 '22 04:12

Sampson