Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capturing text in a link (<a>) element on click

I need to capture the text between <a> and </a> tags and cause a pop up message.I tried to do this as follows.However,what makes it difficult is that I cannot give id's to the links since the links are dynamically generated.So I tried to give them a class and used jquery to select the element.

Then ,I am not sure how the currently clicked element can be selected using jquery.

Suppose,the links generated are as follows

<a href="#" class="mylinkclass"> first link </a> <br>
<a href="#" class="mylinkclass"> second link </a> <br>
<a href="#" class="mylinkclass"> third link </a> <br>
<a href="#" class="mylinkclass"> fourth link </a> <br>

In javascript, I am not sure how the currently clicked element can be selected using jquery. I know that $('.mylinkclass') would return an array of the above 4 links.How can I write the selector code?

$(document).ready(function(){
   $('.mylinkclass').click(function(){getLinkText();});
}

function getLinkText(){
    alert($(this).text());
    return false;
}
like image 667
damon Avatar asked Mar 15 '26 16:03

damon


2 Answers

Change this...

 $('.mylinkclass').click(function(){getLinkText();});

to this...

 $('.mylinkclass').click(getLinkText);

So that you're assigning the function directly as the handler. That way its this value will be a reference to the element clicked.


If there was other work to be done before calling getLinkText, you could either pass the element by passing this as an argument...

 $('.mylinkclass').click(function(){
     // do other work
     getLinkText(this);
 });

function getLinkText(el){

    alert($(el).text());
    return false;
}

Or by using .call or .apply to make this in the function have the same value...

 $('.mylinkclass').click(function(){
    // do other work
    getLinkText.apply(this, arguments);
 });

function getLinkText(){

    alert($(this).text());
    return false;
}
like image 68
Justin Avatar answered Mar 17 '26 04:03

Justin


Your this reference is lost when you call it from inside an anonymous function

$('.mylinkclass').click(function(){
   alert($(this).text());
   return false;
});

or

$('.mylinkclass').click(getLinkText);

function getLinkText(){
//..

or

$('.mylinkclass').click(function () {
   getLinkText(this);
});

function getLinkText(that){
   alert($(that).text());
   return false;
}
like image 27
Selvakumar Arumugam Avatar answered Mar 17 '26 05:03

Selvakumar Arumugam