Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

onclick - # or javascript:void(0)?

I do not intend to start a debate.

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 ?

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

Are those assumptions correct?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

Further explanation:

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.

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:

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);

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

(the code above is an example for W3C compatible browsers, IE is a bit different)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...