# 还是 javascript:void(0)? [英] # or javascript:void(0)?

查看:16
本文介绍了# 还是 javascript:void(0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不打算开始辩论.

如果我们想利用onClick事件,我们应该以某种方式禁用href来触发.- 这是正确的吗?

If we want to make use of the onClick event, we should, on a certain way to disable the href to trigger. - Is this correct ?

如果以上是正确的,我相信 javascript:void(0) 具有不触发滚动行为的优点.

If the above is correct, I believe that javascript:void(0) has the advantage of NOT triggering the scroll behavior.

这些假设正确吗?

注意:我不打算搜索嵌合体,但我的任务是找到一种方法以跨浏览器的方式设置按钮样式,而不会(完全)可访问性命中,也不会受到黑客攻击和怪癖.

Note: I do not intend to search for a chimera, but my quest is about finding a way to style buttons in a cross-browser way with no accessibility hit (at all), without hacks and quirks.

推荐答案

如果你想阻止点击链接,你应该添加 event.preventDefault() 在您的点击处理程序 (event.returnValue = false; 在 IE 中).

If you want to prevent following the link, you should add event.preventDefault() in your click handler (event.returnValue = false; in IE).

您似乎只是关注链接的外观,而不是其功能(或用途).如果是这样,您可以使用带有 CSS 的 button相应地设置样式.

It seems that you are just after the look of a link and not its functionality (or purpose). If so, you can use a button with CSS to style it accordingly.

应避免与 href 内容 #javascript:void(0) 建立真正的链接.

Having real links with href contents # or javascript:void(0) should be avoided.

进一步说明:

使用链接只是为了让某些东西可点击"是不好的.链接具有独特的句法含义.由于您可以为每个元素分配一个 click 事件处理程序,因此您可以使用任何其他元素.

Using a link just to have something "clickable" is not good. A link has a distinct syntactical meaning. As you can assign a click event handler to every element, you can use any other element for that.

语法上最正确的一个(imo)是 button 因为您仍然可以使用 tab 在它们上导航.如果您愿意,您可以使用 CSS 设置它们的样式,使它们看起来像一个链接(查看此示例).

The syntactically most correct one (imo) would be button as you will still have the possibility to use tab to navigate on them. You can style them with CSS to make them look like a link if you want to (see this example).

现在关于防止默认操作:

Now regarding preventing the default action:

假设您有一个 normal 链接,该链接具有正确的 href 值,并且您想要拦截点击.在您分配给元素的点击处理程序中,例如

Assuming you have a normal link with a proper href value and you want to intercept the click. In the click handler you assign to the element, e.g.

link.addEventListener('click', function(event){
    // some code
    event.preventDefault();
}, false);

使用 event.preventDefault() 可以防止默认操作,在链接的情况下,会跟​​随 URL.

using event.preventDefault() prevents the default action, which in case of a link, is following the URL.

(上面的代码是W3C兼容浏览器的例子,IE有点不同)

这篇关于# 还是 javascript:void(0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆