I usually just use # to attach events to click-able elements without a url, but I was thinking about it and feel like it is a little hacky. Is there a better way to do this?
<a href="#"><img src="images/click_here.gif"/></a>
$('a').click(function(event){
alert('you clicked on the click button')
});
My favorite trick is to just attach the click handler to any old element, then use CSS to set cursor: pointer
on it so it looks clickable. Bonus points if you add :hover
and :active
states to really tip the user off.
Example HTML:
<img src="images/click_here.gif" id="click-here-button" />
JS:
$("#click-here-button").click(function () {
alert("You clicked on the click button.");
});
CSS:
#click-here-button
{
cursor: pointer;
}
If you're using jQuery I think anything can be clickable:
$('elementToClick').click(
function(){
alert('you clicked on a clickable thing');
});
You could use the hover()
method to simulate a hyperlink-look:
$('elementToClick').hover(
function(){
$(this).addClass('clickable'); /* or
$(this).css('cursor','pointer'); */
},
function(){
$(this).removeClass('clickable'); /* or
$(this).css('cursor','auto'); */
});
$('elementToClick).click(
function(){
alert('you clicked the clickable thing');
if (this.tagName == 'A') {
return false;
}
});
Using CSS:
.clickable {
cursor: pointer;
}
Depends on the context. If the click action is supposed to link somewhere (even if you intercept that action), then that's what <a />
means. Be happy with it. If you're triggering some other "non-navigation" functionality, I'd just put a click-handler on the <img>
and set an appropriate cursor in CSS. Personal choice, to be honest.
Use javascript:void(0); instead of "#"
<a href="javascript:void(0);"><img src="images/click_here.gif"/></a>
This way you won't add the extra "#" in the URL.
How about this:
<input type="image" src="http://www.google.com/images/logos/ps_logo2.png">
Then just add an event handler and you're golden. :)
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.