I have a simple click handler that will alert its link’s href as in:
<a id="link" href="http://www.google.com">Google</a>
$('a#link').on('click', function() {
alert($(this).attr('href'));
});
How can I separate the function (and how to call it) so that it can be called by another click handler?
function showHref() {
/* What to do here because $(this) won't resolve to <a> anymore. */
}
// I'd like a#another-link to be able to call that same function above.
<a id="another-link" href="http://www.microsoft.com">Microsoft</a>
$('a#another-link').on('click', /* How to call showHref? */);
Thanks.
You could do something like this:
In this code,
thisinside theshowHrefwill refer to the link being clicked, since jQuery makes sure that the link being clicked is the calling context (using.call()which you may want to read up on). If, however, you were to manually callshowHref,thiswould not refer to your link.If you want a definition of
showHrefthat you could both call manually, and bind through jQuery, it would probably be neatest to pass the reference as a parameter:In that case, you’d have to adjust your listeners as follows:
But it is also possible to combine selectors: