哪些"href"值应用于 JavaScript 链接,"#"或"JavaScript: void (0)"?

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {
    alert("myJsFunc");
}
<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>

or

function myJsFunc() {
    alert("myJsFunc");
}
 <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

转载于:https://stackoverflow.com/questions/134845/which-href-value-should-i-use-for-javascript-links-or-javascriptvoid0

weixin_41568134
MAO-EYE Be, and before I get the question "how does making links tabbable help physically disabled people who can only move their neck?", there are devices that emulate keyboard control through head movement designed specifically for people with physical disabilities.
接近 2 年之前 回复
weixin_41568134
MAO-EYE Be, it's more important for companies that don't want to be sued by army veterans who can only use their chin to move, or blind people. If you want to be hostile towards people with physical disabilities visiting your website, that's your prerogative. But don't try to convince others to follow bad practices.
接近 2 年之前 回复
csdnceshi74
7*4 1/ do people really use tab to navigate through links? I rarely ever saw anyone do this but maybe there is data proving me wrong. Another point is that it’s irrelevant for touch screens. 2/ the screen reader topic is overly used imo, again (unfortunately) there is very little data available regarding that topic so it could well be totally irrelevant (i.e. no one uses your website via screen reader, or your website is already totally inaccessible by screen readers). I posted a question regarding screen reader usage in the US a few years back (hence my opinion), will try to find it
接近 2 年之前 回复
weixin_41568134
MAO-EYE Be, the reason to use an anchor instead of a span is for accessibility. Links may be tabbed to, and are read to a screen reader in a special manner. Of course, a button usually makes more sense in many cases where a link is used for dynamic functionality.
大约 2 年之前 回复
weixin_41568196
撒拉嘿哟木头 i use this <a href="#" onclick="javascript:myJsFunc();return false;">Run JavaScript Code</a> in some browsers javascript in href could be ignored, although google seo will mark as a broken link javascript:void(0) in href
大约 4 年之前 回复
weixin_41568127
?yb? If you program SPA, then both approaches are bad because do not maintain a navigation history. Some solution is actually specify your function as href value allowing a browser to push it a navigation history and keep a Backspace key functional.
大约 4 年之前 回复
csdnceshi68
local-host Why not just use a blank <a>, without a href? It's perfectly valid, and accomplishes the same as javascript:void(0).
4 年多之前 回复
weixin_41568208
北城已荒凉 Timo Huovinen: The problem then becomes keyboard accessibility. Without the href you cannot focus and activate the link with keyboard.
4 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 On Safari (mobile) option 2 might have a hard time displaying correctly?
接近 5 年之前 回复
csdnceshi69
YaoRaoLov What about, have no href attribute at all, only keep the onclick, ng-click, (click) or whatever? if you are worried about the pointer cursor missing, add a { cursor: pointer; } to your css file. This will also prevent anyone from trying to open the link in a new tab.
接近 5 年之前 回复
csdnceshi65
larry*wei In HTML5 the href attribute is no longer required, so you can use this format: <a onclick="myJsFunc();">...</a>
大约 5 年之前 回复
csdnceshi70
笑故挽风 Link is supposed to act like a link, not like a button. What you really need here is a button styled as link.
接近 6 年之前 回复
csdnceshi74
7*4 a <button type="button"></button> could do the job yes. type="button" removes the default submit behavior, which you might not want if all you want is a "pure javascript hook". see developer.mozilla.org/en-US/docs/Web/HTML/Element/button
大约 6 年之前 回复
csdnceshi75
衫裤跑路 You're right, a link is a connection from one web resource to another and not a simple UI element. But I would suggest to use a button, as we want something to happen after clicking an element - that's why we have this element in HTML. See also stackoverflow.com/a/8525002/1384441
大约 6 年之前 回复
csdnceshi74
7*4 First thought when looking at this: "why would you use an <a> tag if what you want to do is NOT to open another page via native browser feature but rather have some javascript 'action' to be triggered? simply using a span tag with a class of js-trigger would probably much better". Or am I missing something?
大约 6 年之前 回复
csdnceshi61
derek5. Just do <a href="javascript:myJsFunc()">, it works fine, and not only on click but also on keyboard Enter, via a context menu, etc.
6 年多之前 回复
csdnceshi76
斗士狗 It depends which browser you use. IE and FF "break" by loading the return value ("false", in this case) as a new url. Chrome circumvents the href behavior and merely executes the function.
6 年多之前 回复
csdnceshi56
lrony* That jsfiddle does not appear to break the page. Has it changed? I like giving an indication in the href attribute of what will occur when I click an <a/>.
6 年多之前 回复
csdnceshi51
旧行李 javascript:; is a lot quicker to type than javascript:void(0)
接近 7 年之前 回复
weixin_41568184
叼花硬汉 Why not just <a href="javascript:;" onclick="myEvent()"?
接近 7 年之前 回复
csdnceshi55
~Onlooker - If myJsFunc() has a return value, your page will break. jsfiddle.net/jAd9G You'd still have to use void like so: <a href="javascript:void myJsFunc();">. But then, the behavior would still differ. Invoking the link via context menu does not trigger the click event.
大约 7 年之前 回复
csdnceshi71
Memor.の Unless I'm missing something, <a href="javascript:void(0)" onclick="myJsFunc();"> makes absolutely no sense. If you must use the javascript: psuedo-protocol, you don't need the onclick attribute as well. <a href="javascript:myJsFunc();"> will do just fine.
7 年多之前 回复

30个回答

I would honestly suggest neither. I would use a stylized <button></button> for that behavior.

button.link {
  display: inline-block;
  position: relative;
  background-color: transparent;
  cursor: pointer;
  border: 0;
  padding: 0;
  color: #00f;
  text-decoration: underline;
  font: inherit;
}
<p>A button that looks like a <button type="button" class="link">link</button>.</p>

This way you can assign your onclick. I also suggest binding via script, not using the onclick attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.


If you MUST use an A element, use javascript:void(0); for reasons already mentioned.

  • Will always intercept in case your onclick event fails.
  • Will not have errant load calls happen, or trigger other events based on a hash change
  • The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.

NOTE: You can replace the 0 with a string such as javascript:void('Delete record 123') which can serve as an extra indicator that will show what the click will actually do.

</div>
csdnceshi51
旧行李 This answer should be up top. If you are having this dilemma, chances are you are actually in need of a button. And IE9 is quickly losing market shares, fortunately, and the 1px active effect should not prevent us to use semantic markup. <a> is a link, it's meant to send you somewhere, for actions we have <button>'s.
4 年多之前 回复
weixin_41568131
10.24 Then use a <clickable> element. Or a <clickabletim> if you prefer. Unfortunately, using a non-standard tag or a plain div might make it difficult for keyboard users to focus the element.
大约 5 年之前 回复
csdnceshi56
lrony* DIV is not semantic.
5 年多之前 回复
csdnceshi52
妄徒之命 I use a DIV tag. Easy styling, no fuss.
5 年多之前 回复
csdnceshi56
lrony* that will have the same issue with older IE versions... I've used the <a href="javascript:void(0)" onclick="...">...</a> method enough that it works... just suggesting that it's less than friendly for declaring intent with markup.
接近 6 年之前 回复
csdnceshi60
℡Wang Yan Then don't use <button> but an input type=button instead?
接近 6 年之前 回复
csdnceshi56
lrony* Yeah, unfortunately, any styling of buttons is more problematic with IE... I still feel it's probably the most appropriate approach, not that I don't break my own rules on occasion.
大约 8 年之前 回复
csdnceshi79
python小菜 In IE8/IE9, I'm unable to remove the 1px "3D" offset in the button's :active state.
大约 8 年之前 回复

Doing <a href="#" onclick="myJsFunc();">Link</a> or <a href="javascript:void(0)" onclick="myJsFunc();">Link</a> or whatever else that contains an onclick attribute - was okay back five years ago, though now it can be a bad practice. Here's why:

  1. It promotes the practice of obtrusive JavaScript - which has turned out to be difficult to maintain and difficult to scale. More on this in Unobtrusive JavaScript.

  2. You're spending your time writing incredibly overly verbose code - which has very little (if any) benefit to your codebase.

  3. There are now better, easier, and more maintainable and scalable ways of accomplishing the desired result.

The unobtrusive JavaScript way

Just don't have a href attribute at all! Any good CSS reset would take care of the missing default cursor style, so that is a non-issue. Then attach your JavaScript functionality using graceful and unobtrusive best practices - which are more maintainable as your JavaScript logic stays in JavaScript, instead of in your markup - which is essential when you start developing large scale JavaScript applications which require your logic to be split up into blackboxed components and templates. More on this in Large-scale JavaScript Application Architecture

Simple code example

// Cancel click event
$('.cancel-action').click(function(){
    alert('Cancel action occurs!');
});

// Hover shim for Internet Explorer 6 and Internet Explorer 7.
$(document.body).on('hover','a',function(){
    $(this).toggleClass('hover');
});
a { cursor: pointer; color: blue; }
a:hover,a.hover { text-decoration: underline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cancel-action">Cancel this action</a>

A blackboxed Backbone.js example

For a scalable, blackboxed, Backbone.js component example - see this working jsfiddle example here. Notice how we utilize unobtrusive JavaScript practices, and in a tiny amount of code have a component that can be repeated across the page multiple times without side-effects or conflicts between the different component instances. Amazing!

Notes

  • Omitting the href attribute on the a element will cause the element to not be accessible using tab key navigation. If you wish for those elements to be accessible via the tab key, you can set the tabindex attribute, or use button elements instead. You can easily style button elements to look like normal links as mentioned in Tracker1's answer.

  • Omitting the href attribute on the a element will cause Internet Explorer 6 and Internet Explorer 7 to not take on the a:hover styling, which is why we have added a simple JavaScript shim to accomplish this via a.hover instead. Which is perfectly okay, as if you don't have a href attribute and no graceful degradation then your link won't work anyway - and you'll have bigger issues to worry about.

  • If you want your action to still work with JavaScript disabled, then using an a element with a href attribute that goes to some URL that will perform the action manually instead of via an Ajax request or whatever should be the way to go. If you are doing this, then you want to ensure you do an event.preventDefault() on your click call to make sure when the button is clicked it does not follow the link. This option is called graceful degradation.

</div>
csdnceshi77
狐狸.fox According to sitepoint.com/community/t/anchors-without-href/6690/4 Screen-readers are fine with anchors that don't use href. The use of "#" is actually worse as it adds open in new tab functionality which only sends the use back to the original page at the top without the desired functionality.
3 年多之前 回复
csdnceshi51
旧行李 I'm agreeing with my two pre-posters. Without the href you are not even able to navigate through the links by using tabs. This answer should be deleted!
大约 4 年之前 回复
csdnceshi68
local-host No, no, no!!! Don't EVER do this! You have just killed accessibility. Users with screen readers will no longer be able to use your application.
5 年多之前 回复
weixin_41568131
10.24 The missing href attribute is a problem. Many browsers don't display the link mouse cursor (yes, it can be added in CSS, but this is complicating things already) and I've seen some accessibility software ignore links without href (they are treated as just text). This answer has good ideas but the real world isn't as neat.
接近 7 年之前 回复
csdnceshi55
~Onlooker If you care about making your web application accessible (and you should), simplicity and sanity argues for href. Madness lies in the direction of tabindex.
大约 7 年之前 回复
weixin_41568127
?yb? With all those "notes" that are hard to solve (setting a tabindex is asking for trouble on a complex page!). Far better to just do javascript:void(0). That is the pragmatic answer, and the only sensible answer in the real world.
大约 7 年之前 回复
weixin_41568184
叼花硬汉 A full disagree here. While I also promote unobtrusive JavaScript, an anchor that has a "javascript:;" and it's actual events bound somewhere else is not bad practice. And it is always better than leaving the attribute out completely.
大约 7 年之前 回复
csdnceshi52
妄徒之命 It would make more sense to add 2 classes, one called cancel and the other action, then apply the css only to .action and the javascript only to .action.cancel
7 年多之前 回复
csdnceshi80
胖鸭 I find this answer to be overly dogmatic. There are times when you just want to apply the JS behavior to 1 or 2 a href's. In that case it's overkill to define extra CSS and inject a whole JS function. In some cases (e.g. adding content via a CMS) you are actually not allowed to inject new CSS or standalone JS, and inline is all you can do. I don't see how the inline solution is any less maintainable in practice for 1 or 2 simple JS a href's. Always be suspicious of broad general statements on bad practice, including this one :)
7 年多之前 回复
csdnceshi74
7*4 Beware: the link-styled button approach suggested here is plagued by the unavoidable "3d" active state in IE9 and lower.
大约 8 年之前 回复
csdnceshi73
喵-见缝插针 I tend to agree with this answer, but there is another issue that arises from omitting the href attribute. In many browsers if you click the link multiple times very quickly it will actually select text on the page. Setting the href solves that particular problem which is not easy to fix otherwise.
大约 8 年之前 回复
csdnceshi70
笑故挽风 Be careful, leaving href attributes off is not cross browser compatible and you will lose out on things such as hover effects in internet explorer
8 年多之前 回复

'#' will take the user back to the top of the page, so I usually go with void(0).

javascript:; also behaves like javascript:void(0);

csdnceshi66
必承其重 | 欲带皇冠 At the first release of angular the author said something like, "best practices follow necessity," right before he put his script tags at the very bottom of the page.
3 年多之前 回复
csdnceshi52
妄徒之命 any anchor that doesn't actually exist in the document (e.g. #_) does the same trick, with the same drawbacks.
大约 6 年之前 回复
csdnceshi80
胖鸭 The shebang (#!) does the trick but it's definitely bad practice.
6 年多之前 回复
weixin_41568184
叼花硬汉 Any use of # or void(0) is bad practice and shouldn't be encouraged.
大约 7 年之前 回复
weixin_41568196
撒拉嘿哟木头 If you have a base href, then # or #something will take you to that anchor on the base href page, instead of on the current page.
8 年多之前 回复
csdnceshi76
斗士狗 using "#someNonExistantAnchorName" works well because it has nowhere to jump to.
接近 12 年之前 回复
weixin_41568208
北城已荒凉 Returning false in the event handler doesn't avoid that if JavaScript the JS doesn't run successfully.
接近 12 年之前 回复
weixin_41568127
?yb? The way to avoid that is to return false in the onclick event handler.
接近 12 年之前 回复

Neither.

If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.

If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers.

I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.

Check out Unobtrusive JavaScript and Progressive enhancement (both Wikipedia).

csdnceshi60
℡Wang Yan Quite astonishing, such high voted answer that event doesn't attempt to answer the question.
大约 2 年之前 回复
weixin_41568196
撒拉嘿哟木头 Button is perhaps the best choice. I suppose the main point is that the HTML element shouldn't be selected based on its default presentation appearance, but rather its significance to the structure of the document.
大约 6 年之前 回复
csdnceshi73
喵-见缝插针 I wouldn't use a div or span either; frankly, this seems like the very thing <button> was made for. But agreed: it probably shouldn't be specifically an <a> if there's no suitable place for it to link to.
大约 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 It was meant as a "it's completely unnecessary to even use an anchor tag if you aren't using it as an anchor tag." I was questioning the logic of suggesting to "inject the anchor tag into the document with JavaScript and the appropriate click event handlers." Everything in that sentence is correct except you shouldn't be using an anchor tag. Use a div, or a span, or something else.
大约 6 年之前 回复
csdnceshi72
谁还没个明天 Another +1 for neither. I'm sick of opening blank "javascript:void(0)" tabs using middle mouse button.
6 年多之前 回复
csdnceshi62
csdnceshi62 +1 for neither, but there are over approaches. Fact remains use of either javascript: or # are both bad practices and not to be encouraged. Nice articles btw.
大约 7 年之前 回复
csdnceshi73
喵-见缝插针 It was pretty badly worded, then. It seemed more like a "why would you want to do this?". Even as i read it over again, it still seems that way.
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 That's the same point I just made...
7 年多之前 回复
csdnceshi73
喵-见缝插针 If you inject the element via script, it won't be present when JS is disabled. Since it's entirely broken unless JS is running, it really shouldn't even exist unless JS is running.
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 Why inject the anchor tag at all if it is merely meant to be used to allow an element to be a) clicked b) display the "pointer" cursor. It seems irrelevant to even inject an anchor tag in this scenario.
7 年多之前 回复
csdnceshi65
larry*wei Can you give an example of how one might "inject the anchor tag into the document with JavaScript and the appropriate click event handlers"?
7 年多之前 回复

The first one, ideally with a real link to follow in case the user has JavaScript disabled. Just make sure to return false to prevent the click event from firing if the JavaScript executes.

<a href="#" onclick="myJsFunc(); return false;">Link</a>

If you use Angular2, this way works:

<a [routerLink]="" (click)="passTheSalt()">Click me</a>.

See here https://stackoverflow.com/a/45465728/2803344

csdnceshi62
csdnceshi62 my work is billed to clients at $100 per hour. If I was to make every javascript link on my current project work without javascript, it would cost about $300,000 (there are thousands of links like that). There are not enough people visiting this website to justify the cost. Instead we would simply tell them "oh, that button won't work unless you turn javascript on." and so far we have never had any complaints. I always put a fallback in when practical, but often it simply isn't worth it. As with most things, you should learn the pros/cons of each solution and choose appropriately.
大约 7 年之前 回复
csdnceshi64
游.程 Personally both @Fczbkk and StevePaulo approaches are better, regardless of whether a link has a hyperlink or not you should accommodate those who are viewing your site without javascript and gracefully de-grade how ever you see fit.
大约 7 年之前 回复
csdnceshi64
游.程 And that's a compelling reason because? Just because others do it doesn't mean you have to follow suit I stand by opinion and you are entitled to yours.
大约 7 年之前 回复
csdnceshi62
csdnceshi62 that's nice in theory, but in the real world there are plenty of situations where there is no fallback URL. The "cancel" button on this comment box for example, has no fallback. StackOverflow has chosen not to have a href attribute at all. This makes it invalid according to the HTML spec and also causes some minor bugs in old browsers (they treat it a being an anchor instead of a clickable element).
大约 7 年之前 回复
csdnceshi64
游.程 Neither is right, the href should contain a URL that can be used as a fallback. Good example is initiating popups with javascript, use the URL from the href to power the popup and when javascript is disabled the link will take you to the page that would have been loaded by your popup as a fallback.
大约 7 年之前 回复
csdnceshi71
Memor.の From what I found, you have to use onclick="event.preventDefault(); myJsFunc(); return false;".
大约 8 年之前 回复
csdnceshi62
csdnceshi62 The problem with # is that if the javascript doesn't run for some particular reason, it will break, sometimes very badly (eg: if you have a base href on the page, # will usually take the user to a completely different webpage). On the other hand with void(0), if the javascript has a problem it simply won't do anything. Another nice benefit of void(0) is it takes away any necessity for cancelling the click event, which is easily forgotten and makes it impossible to attach multiple observers to the event.
8 年多之前 回复
csdnceshi56
lrony* The issue is if myJsFunc throws an error, it won't be captured for the return false.
接近 9 年之前 回复
csdnceshi78
程序go My web apps are designed to degrade gracefully, so the link will still be a useful page. Unless your web app is a chat client or something that interactive, this should work if you put in the time to design with degradation in mind.
大约 11 年之前 回复
csdnceshi77
狐狸.fox I would assume (hope) that something like this would only be for showing a popup or something similarly simple. In that case, the default would be the popup page url. If this is part of a web application, or having JS disabled would totally break the page, then this code has other issues...
大约 11 年之前 回复
csdnceshi78
程序go "ideally with a real link to follow in case the user has JavaScript disabled", it should be going to a useful page not #, even if it's just an explanation that the site needs JS to work. as for failing, I would expect the developer to use proper browser feature detection, etc before deploying.
接近 12 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 So in user agents with JavaScript enabled and the function supported this run a JavaScript function, falling back (for user agents where the JS fails for whatever reason) to a link to the top of the page? This is rarely a sensible fallback.
接近 12 年之前 回复

I use javascript:void(0).

Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:

function doSomething() {
    //Some code
    return false;
}

But then they forget to use return doSomething() in the onclick and just use doSomething().

A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.

A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:

onclick="someFunc.call(this)"

OR

onclick="someFunc.apply(this, arguments)"

Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside.

So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:

Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.

OR

Use href="javascript:void(0)"

The second is clearly much easier to communicate.

csdnceshi75
衫裤跑路 I noticed that, when I leave a tag without href attribute, the browser will automatically add href="javascript:;" to it. So can we just leave a tag without href instead of adding href="javascript:void(0)" or href="#"?
大约 2 年之前 回复
weixin_41568174
from.. Don't use <a> if your sole purpose is just to trigger js code. Use <button> instead.
3 年多之前 回复
weixin_41568184
叼花硬汉 Hi Anthony , I would like to ask you from where did you learn JavaScript ? Which resource ? I spend a lot of time on documentation but I don't learn sufficient enough.
3 年多之前 回复
weixin_41568134
MAO-EYE Using href="javascript:myFunc()" in Firefox opens a new tab with the text "javascript:myFunc()" in it, instead of executing the function.
3 年多之前 回复
csdnceshi52
妄徒之命 This answer doesn't actually explain why anchor links don't work
3 年多之前 回复
csdnceshi68
local-host Can you tell me more about the different between href="javascript:void(0)" and href="javascript:;"?
接近 4 年之前 回复
csdnceshi71
Memor.の "the final return false; will not execute if the called function throws an error." -> This problem is easily solved by using e.preventDefault() at the top, instead of relying on the return value. This has been the best way to do this for years. I am truly baffled why people still go around using return false.
大约 4 年之前 回复
weixin_41568110
七度&光 Again I fall a foul of not looking at the timestamp...sorry was reading the comments back to front.
大约 4 年之前 回复
csdnceshi65
larry*wei If I could go back in time I wouldn't have written that, certainly not so snarkily. I've changed my views. If you want an element that runs JS on click, don't use a anchor, just attach a handler via JS and CSS it however you'd like. Sorry to all I offended.
大约 4 年之前 回复
weixin_41568110
七度&光 Glad I don't work with you! A link is a link however you dress it up, it's hacks like this that create more problems then they solve. It's 2016 no one should be using # or javascript:void(0) now it's poor practice whether you want to just run JavaScript or not. It's inaccessible, can cause unexpected behaviours, doesn't gracefully de-grade. It's not "panic mongering" just good sense.
大约 4 年之前 回复
csdnceshi53
Lotus@ I have noticed another con of using "javascript:void(0)" in your href as it regards to using Google Analytics or Webtrends. First of all I assume you are using "javascript:void(0)" in your achor tag because it is firing a function that causes some interaction that does not leave the current URL. In my experiences, using "javascript:void(0)" will cause your anchor tag to fire twice which has been brought to my attention by our QA department. As small as an issue it may seem, it makes using "javascript:void(0)" quite an issue for my strict QA dept. Hope this helps someone out.
4 年多之前 回复
csdnceshi80
胖鸭 Of note - in today's world of client-side applications that use client-side routing, using # is often not an option anymore for a no-op.
4 年多之前 回复
csdnceshi77
狐狸.fox This is the worst answer. Use links for links, not javascript. The javascript: pseudo protocol was designed to replace the current document with the value returned from the expression. When the expression used evaluates to an undefined value (as some function calls do), the contents of the current page are not replaced. Regardless, some browsers interpret this as navigation and will enter into a 'navigation' state where GIF animations and plugins (such as movies) will stop and navigational features such as META refresh, assignment to location.href, and image swaps fail.
4 年多之前 回复
csdnceshi76
斗士狗 I had compatibility problem with ie8 and javascript:void(0) onclick did not fired on attached events
大约 5 年之前 回复
weixin_41568127
?yb? Why not just not use javascript:void(0) altogether for these cases? Why not just use a data-* attribute and then use querySelector() (or equivalent) and add the event listeners for them?
5 年多之前 回复
csdnceshi54
hurriedly% i used 'javascript:void(0)' to prevent onclick page jumps, from here
5 年多之前 回复
weixin_41568126
乱世@小熊 href="javascript:void(0)" opens a blank page on middle click, whereas href="#" opens a copy of the current page on middle click. I think the latter is much worse, especially if you're on a heavy page. Note also this happens only in Firefox: jakub-g.github.io/accessibility/onclick
接近 6 年之前 回复
csdnceshi63
elliott.david History lesson: The use of the hash # was a hack to start with. Older browsers (ie IE) wouldn't make A tags clickable without a non-empty HREF attribute, and many elements could never be clickable; hash was the only way to make something clickable and prevent navigation at the same time, since some browsers then also didn't run Javascript yet. No modern (even older IEs that are still in use today) have those problems anymore; so it's better to stick with standards and avoid both of these hacks to do it the standard appropriate way as mentioned in other answers.
接近 6 年之前 回复
csdnceshi65
larry*wei This is the best answer, because it actually answers the question. Most of you seem to have missed the "a link that has the sole purpose to run JavaScript code" part. All your jabbering about links in new tabs, graceful degrading, and web dev -ilities is just off topic web standards / best practice panic mongering. Not having a href might be best, but that actually decreases accessibility and can result in other unexpected behaviors.
大约 6 年之前 回复
csdnceshi56
lrony* web standards: you should only use href if you have a valid url and you should put that url between href"" prior to page load. both of your methods are horrible for accessibility, usability, every other -ility that applies to web dev
6 年多之前 回复
weixin_41568131
10.24 What about just leaving href="" blank like so. I've read that works pretty well, and does in my experience. And it's still valid
6 年多之前 回复
csdnceshi61
derek5. How is the 2nd reason an advantage to the developer? I would not like things to carry on as usual when an error was thrown.
6 年多之前 回复
weixin_41568126
乱世@小熊 good question; this seems to be working for me in modern browsers: window.onhashchange = function (evt) { if(evt.newURL.endsWith("#void")) { history.replaceState(null, null, evt.oldURL); } } Haven't tested with IE, though MDN says it doesn't support evt.newURL and evt.oldURL (at least IE8). replaceState is supported from IE10.
6 年多之前 回复
weixin_41568131
10.24 I like the idea of using a generic hashtag the best. How would I go about preventing the url from updating in the browser? That's my only thing about this... Thanks!
6 年多之前 回复
csdnceshi59
ℙℕℤℝ You can use "#" and then bind a click event to all links with "#" as the href. This would be done in jQuery with: $('a[href="#"]').click(function(e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; });
6 年多之前 回复
weixin_41568126
乱世@小熊 Fast-forward to 2013: javascript:void(0) violates Content Security Policy on CSP-enabled HTTPS pages. One option would be then to use href='#' and event.preventDefault() in the handler, but I don't like this much. Perhaps you can establish a convention to use href='#void' and make sure no element on the page has id="void". That way, clicking a link to non-existing anchor will not scroll the page.
接近 7 年之前 回复
csdnceshi67
bug^君 The next two answers are far better and reasonable than this one. Also the first two arguments are invalid because event.preventDefault() is there exactly to prevent default behavior (like jumping to the top of the page in this case) and do a better job at it without all the return false; craziness.
大约 7 年之前 回复
weixin_41568110
七度&光 Sorry disagree why does this answer have so many upvotes? Any use of javascript: should be considered bad practice, obtrusive and doesn't graceful de-grade.
大约 7 年之前 回复
csdnceshi55
~Onlooker I always open every link in a new tab and this is the reason why I personally hate it when people use the href="javascript:void(0)" method
7 年多之前 回复

Depending on what you want to accomplish, you could forget the onclick and just use the href:

<a href="javascript:myJsFunc()">Link Text</a>

It gets around the need to return false. I don't like the # option because, as mentioned, it will take the user to the top of the page. If you have somewhere else to send the user if they don't have JavaScript enabled (which is rare where I work, but a very good idea), then Steve's proposed method works great.

<a href="javascriptlessDestination.html" onclick="myJSFunc(); return false;">Link text</a>

Lastly, you can use javascript:void(0) if you do not want anyone to go anywhere and if you don't want to call a JavaScript function. It works great if you have an image you want a mouseover event to happen with, but there's not anything for the user to click on.

csdnceshi62
csdnceshi62 Surprise surprise.
2 年多之前 回复
weixin_41568110
七度&光 The only downside with this (from memory, I may be wrong) is that IE doesn't consider an A to be an A if you don't have a href inside it. (So CSS rules won't work)
接近 12 年之前 回复

I usually go for

<a href="javascript:;" onclick="yourFunction()">Link description</a>

It's shorter than javascript:void(0) and does the same.

csdnceshi74
7*4 I do the same too!
4 年多之前 回复

If there is no href maybe there is no reason to use an anchor tag.

You can attach events (click, hover, etc.) on almost every element, so why not just use a spanor a div?

And for users with JavaScript disabled: if there isn't a fallback (for example, an alternative href), they should at least not be able to see and interact with that element at all, whatever it is an <a> or a <span> tag.

When I've got several faux-links, I prefer to give them a class of 'no-link'.

Then in jQuery, I add the following code:

$(function(){
   $('.no-link').click(function(e){
       e.preventDefault();
   });
});

And for the HTML, the link is simply

<a href="/" class="no-link">Faux-Link</a>

I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).

<a href="javascript:void(0)" class="no-link">Faux-Link</a>

Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.

共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问