My goal is to retreive the text of an anchor tag by clicking it. I want this to be inside a function not inline. Example
function getText(){
alert($('this.a').text());
}
I know the above does not work b/c i have tried it.
I don't want this to be by id because i want it to work on all 'a' elements when they are clicked. When i use:
function getText(){
alert($('a').text());
}
it returns ALL text within ALL the 'a' tags on my page. What i am trying to accomplish is simply returning only the text of the anchor tag i clicked. I think it has something to do with using $(this) along with the 'a' tag but i can't seem to figure it out.
Again i want to be able to call this function for all a tags on my page without having to write a function for each id so that is why i want to use "this". Thank you.
You just want $(this).text()
:
function getText() {
alert($(this).text());
}
And, of course, you should be handling your event like so:
$('a').click(getText);
It's just the same as a separate function as it would be with in inline one:
$("selector_for_the_anchors_in_question").click(clickHandler);
function clickHandler() {
alert($(this).text());
}
jQuery ensures that when the handler is called, this
is set to the element on which the handler was hooked, and of course to get a jQuery wrapper for that element you use $()
(or jQuery()
in noConflict
mode).
You somehow have to bind the function to the click event.
function getText(){
alert($(this).text()); // `this` is the element clicked
return false; // prevent navigating
}
$("a").click(getText); // bind function to all <a> elements
It's not inlining this way, but honestly I don't see a reason for doing it like this.