Below is a sample of a URL that is in a site (project that I inherited).
When clicking on the link, I need to get the text "Click Link".
I have searched the web and all suggestions do not work.
Any help is appreciated.
<a href="site/page" onclick="loadContent('https://site/page.com');">
<span class="navitem">Click Link</span>
</a>
The text in a span tag.
I’ve tried
$('. navitem').on('click', 'a', function() {
var text = $(this).text();
});
But Console log says $ not defined
.
I also tried
$('a').live('click', function() {
window.location.href = $(this).closest('span').text();
});
3
Answers
In your following jQuery code:
you have deleget event on
a
ofnavitem
which in your case is incorrect. It need to be something like$('a').on('click', '.navitem')
. I have update this click event in following snippet.Similarly, when using
live
method in your, second code you might getthis is because the live API is deprecated has been removed since jQuery 1.9
Your first code snippet contains two misstakes. Change this one by
There was an unnessacry space between ‘.’ and ‘navitem’. Another one was in the on method. I removed the passed parameter ‘a’.
Based on your last comment – underneath your question- you have to wrap this into
Another point is your html code snippet. The presented code makes not sense:
Your a tag overlaps you span tag and the href attribute overlaps the onclick attribute, so the value of href will be executed first. Your added code for span element won’t be executed.