[英]is there a better way to make something click-able other than using <a href=“#”>element</a>
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. 我通常只使用#将事件附加到没有网址的可点击元素,但我正在考虑它并觉得它有点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. 我最喜欢的技巧是将click处理程序附加到任何旧元素,然后使用CSS在其上设置
cursor: pointer
,使其看起来可点击。 Bonus points if you add :hover
and :active
states to really tip the user off. 如果你添加
:hover
和:active
状态以真正提示用户关闭奖励积分。
Example HTML: 示例HTML:
<img src="images/click_here.gif" id="click-here-button" />
JS: JS:
$("#click-here-button").click(function () {
alert("You clicked on the click button.");
});
CSS: CSS:
#click-here-button
{
cursor: pointer;
}
If you're using jQuery I think anything can be clickable: 如果您正在使用jQuery,我认为任何东西都可以点击:
$('elementToClick').click(
function(){
alert('you clicked on a clickable thing');
});
You could use the hover()
method to simulate a hyperlink-look: 您可以使用
hover()
方法来模拟超链接外观:
$('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: 使用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. 如果点击动作应该链接到某个地方(即使你拦截了那个动作),那么这就是
<a />
含义。 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. 如果你正在触发其他一些“非导航”功能,我只需在
<img>
上放置一个click-handler并在CSS中设置一个合适的游标。 Personal choice, to be honest. 个人选择,说实话。
Use javascript:void(0); 使用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. 这样您就不会在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. 然后只需添加一个事件处理程序,你就是金色的。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.