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

查看:153
本文介绍了#或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)有NOT触发滚动行为的优点。

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来相应地设置样式。

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.

进一步说明:

使用链接只是为了点击可点击并不好。链接具有独特的句法意义。由于您可以为每个元素分配单击事件处理程序,因此您可以使用任何其他元素。

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 因为您仍然可以使用标签来导航它们。如果您愿意,可以使用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:

假设您有正常链接到正确的 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天全站免登陆