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;
}
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With