I'm trying to find a way to call a jQuery statement from within an <a>
tag in an href
attribute. My code looks like this:
<a href="javascript:$('#myElement').addClass('test');">
When I click on this link the browser (Firefox) goes to a blank page with:
[object Object]
IMPORTANT: I am using a third-party plugin that generates the anchor tag code so I don't have access to add the code into the onclick event for the <a>
tag. I would also prefer not to have to introduce a function as a wrapper to the statement as we're using AJAX.
The funny thing is, this works:
<a href="javascript:alert('test');">
Is there a reason why jQuery statements don't work in an href
attribute? Is it the leading dollar sign causing issues? Is there a way to make it work?
The return value of a javascript:
URI is the data used to make up the page the browser should go to.
A call to jQuery
will return a jQuery object. A call to alert
will return undefined
(which is treated as a No Content response).
You could wrap the script in a call to void()
(passing the return value of jQuery
as an argument to it), but I'd really advise sorting out the underlying system so you don't have to use javascript:
URIs in the first place.
You can get around this by wrapping the call in a function:
<a href="javascript:(function(){$('#myElement').addClass('test');})()">asdf</a>
But the better bet is using the javascript click event:
<a href="#" onclick="$('#myElement').addClass('test');return false;">asdf</a>
or even better, hooking up elsewhere:
<a href="#" id="somelink">asdf</a>
jQuery(document).ready(function() {
jQuery("#somelink").click(function() {
$('#myElement').addClass('test');
return false;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.