"javascript:void(0);" vs “返回假” vs “preventDefault()”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3498492/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"javascript:void(0);" vs "return false" vs "preventDefault()"
提问by Mike
When I want some link to not do anything but only respond to javascript actions what's the best way to avoid the link scrolling to the top edge of the page ?
I know several ways of doing it, they all seem to work fine :
当我想要一些链接不做任何事情而只响应 javascript 操作时,避免链接滚动到页面顶部边缘的最佳方法是什么?
我知道几种方法,它们似乎都可以正常工作:
<a href="javascript:void(0)">Hello</a>
or
或者
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
  $(document).ready(function() {
    $("#toto").click(function(){
      //...
      return false;
    });
  });
</script>
and even :
乃至 :
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
  $(document).ready(function() {
    $("#toto").click(function(event){
      event.preventDefault();          
      //...
    });
  });
</script>
Do you have any preference ? why ? in which conditions ?
你有什么偏好吗?为什么 ?在什么条件下?
PS: of course the above examples assume you're using jquery but there's equivalents for mootools or prototype.
PS:当然,上面的例子假设你使用的是 jquery,但有 mootools 或原型的等价物。
采纳答案by bobince
Binding:
捆绑:
- javascript:URLs are a horror to be avoided at all times;
- inline event handler attributes aren't brilliant either, but OK for a bit of rapid development/testing;
- binding from script, leaving the markup clean, is typically considered a best practice. jQuery encourages this, but there is no reason you can't do it in any library or plain JS.
- javascript:URL 是一种应始终避免的恐怖内容;
- 内联事件处理程序属性也不是很好,但对于一些快速开发/测试来说还可以;
- 从脚本绑定,使标记保持干净,通常被认为是最佳实践。jQuery 鼓励这样做,但没有理由不能在任何库或普通 JS 中执行此操作。
Responses:
回应:
- In jQuery return falsemeans bothpreventDefaultandstopPropagation, so the meaning is different if you care about parent elements receiving the event notification;
- jQuery is hiding it here but preventDefault/stopPropagationhave to be spelled differently in IE usually (returnValue/cancelBubble).
- 在 jQuery 中return false既是preventDefaultandstopPropagation的意思,如果你关心父元素接收事件通知,意思就不一样了;
- jQuery 将它隐藏在这里,但preventDefault/stopPropagation必须在 IE 中通常拼写不同(returnValue/cancelBubble)。
However:
然而:
- You have a link that isn't a link. It doesn't link anywhere; it's an action. <a>isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has.
- For cases where it really does point to something, like when it opens/closes another element on the page, set the link to point to #thatelementsidand use unobtrusive scripting to grab the element ID from the link name. You can also sniff thelocation.hashon document load to open that element, so the link becomes useful in other contexts.
- Otherwise, for something that is purely an action, it would be best to mark it up like one: <input type="button">or<button type="button">. You can style it with CSS to look like a link instead of a button if want.
- However there are some aspects of the button styling you can't quite get rid of in IE and Firefox. It's usually not significant, but if you really need absolute visual control a compromise is to use a <span>instead. You can add atabindexproperty to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this).
- Another possibility is <input type="image">. This has the accessibility advantages of the button with full visual control, but only for pure image buttons.
- 您有一个不是链接的链接。它不会链接到任何地方;这是一个动作。<a>不是真正的理想标记。如果有人试图用中键单击它,或将其添加到书签或链接具有的任何其他可见性,则会出错。
- 对于它确实指向某些内容的情况,例如当它打开/关闭页面上的另一个元素时,将链接设置为指向#thatelementsid并使用不显眼的脚本从链接名称中获取元素 ID。您还可以嗅探location.hash文档加载以打开该元素,因此该链接在其他上下文中变得有用。
- 否则,对于纯粹的动作,最好将其标记为 one:<input type="button">或<button type="button">。如果需要,您可以使用 CSS 将其样式设置为链接而不是按钮。
- 但是,在 IE 和 Firefox 中,您无法完全摆脱按钮样式的某些方面。它通常并不重要,但如果您确实需要绝对的视觉控制,则可以使用 a<span>来代替。您可以添加一个tabindex属性以使其在大多数浏览器中可以通过键盘访问,尽管这并没有真正标准化。您还可以检测诸如 Space 或 Enter 之类的按键以激活。这有点令人不满意,但仍然很受欢迎(所以,首先,它是这样的)。
- 另一种可能性是<input type="image">。这具有具有完全视觉控制的按钮的可访问性优势,但仅适用于纯图像按钮。
回答by karim79
The only advantage that I can think of to using javascript:void(0)is that it will be supported even by the oldest browsers. That said, I would use one of the other unobtrusiveapproaches you have mentioned:
我能想到的唯一优点javascript:void(0)是即使是最旧的浏览器也会支持它。也就是说,我会使用您提到的其他不显眼的方法之一:
- For most uses, event.preventDefault()andreturn falsecan be used interchangeably.
- event.preventDefault()will prevent the page from reloading, as desired, but will allow the click event to bubble up to the parent. If you want to stop the bubbling, you can use it in conjunction with- event.stopPropagation.
- return falsewill additionally stop the event from bubbling up to the parent.
- 对于大多数用途,event.preventDefault()并且return false可以互换使用。
- event.preventDefault()将根据需要阻止页面重新加载,但将允许单击事件冒泡到父级。如果你想停止冒泡,你可以结合使用它- event.stopPropagation。
- return false还将阻止事件冒泡到父级。
I say 'interchangeably' in the first point above because much of the time we do not care whether or not an event bubbles up to the parent(s). However, when dowe need some fine-tuning, we should consider points two and three.
我在上面的第一点说“可互换”,因为很多时候我们并不关心事件是否冒泡到父级。然而,我们什么时候需要一些微调,我们应该考虑第二点和第三点。
Consider the following example:
考虑以下示例:
<div>Here is some text <a href="www.google.com">Click!</a></div>?
$("a").click(function(e) {
    e.preventDefault();
});
$("div").click(function() {
    $(this).css("border", "1px solid red");
});
?
Clicking on the anchor will prevent the default action of the event from being triggered, so the browser will not redirect to www.google.com. However, the event will still 'bubble up' and cause the div's click event to fire, which will add a border around it. Add e.stopPropagation()or justreturn falseand the div's click event will not fire. You can mess with it here: http://jsfiddle.net/cMKsN/1/
点击锚点会阻止事件的默认动作被触发,因此浏览器不会重定向到www.google.com。但是,该事件仍会“冒泡”并导致 div 的点击事件触发,这将在其周围添加边框。Add e.stopPropagation()or justreturn false不会触发 div 的点击事件。你可以在这里弄乱它:http: //jsfiddle.net/cMKsN/1/
回答by Whit
Dreamweaver uses a nice little trick by default that I've started using.
默认情况下,Dreamweaver 使用了我开始使用的一个不错的小技巧。
<a href='javascript:;'></a>
It's small, it doesn't trip and anchors and it's library agnostic.
它很小,不会绊倒和锚定,而且它与图书馆无关。
回答by Jean Paul A.K.A el_vete
I think that I have seen as well javascript:; around as the web develops, is hard to keep track to the tricks that are available out there.. but this is mainly about accessability (besides javascript:void(0); ) and just a small correction is not javascript:void(0) but javascript:void(0); which means do nothing so pretty much as return false; although not sure if javascript:return false; does the same..
我想我也看过 javascript:; 随着网络的发展,很难跟踪可用的技巧......但这主要是关于可访问性(除了 javascript:void(0); ),只是一个小的更正不是 javascript:void(0)但是 javascript:void(0); 这意味着除了返回 false 之外什么都不做;虽然不确定是否 javascript:return false; 做同样的..
I always use and would suggest to use javascript:void(0); for a couple of reasons.. in my humble opinion, of course.
我总是使用并建议使用 javascript:void(0); 出于几个原因……当然,以我的拙见。
1.) I use it because of the same someone mentioned above.. href="#" is not appropriate as it might indicate going to the top and even in that case '#top' would be more adequate for that case. But also this can trigger something else in your code that makes use of # (hashes) so another reason is to avoid conflicts with other javascript that might be using #. And I tend to look for this when using a plugin for example, and replace them immediately.. href='#' to href='javascript:void(0);' or href='javascript:;'
1.) 我使用它是因为上面提到的那个人.. href="#" 是不合适的,因为它可能表示进入顶部,即使在这种情况下 '#top' 也更适合这种情况。但这也可以触发您的代码中使用#(哈希)的其他内容,因此另一个原因是避免与可能使用#的其他javascript发生冲突。例如,我倾向于在使用插件时寻找这个,并立即替换它们.. href='#' to href='javascript:void(0);' 或 href='javascript:;'
2.) If I want to re-use a function for a group of specific Anchor tags, I can call it with the selector on any attribute without worrying about detecting the click event and preventing the default action and I do it without even thinking of it as a development preference.
2.) 如果我想为一组特定的 Anchor 标签重用一个函数,我可以在任何属性上使用选择器调用它,而不必担心检测点击事件和阻止默认操作,我什至没有考虑它作为一种开发偏好。
3.) In most cases if you are doing link building using javascript:void(0); tries to make a link to not be followed as the old href= rel=nofollow so it avoid indexing links that are actions. I'm not so sure about this one merely because I heard that crawlers and robots can now read even Flash so would not be surprised if they can read javascript links
3.) 在大多数情况下,如果您使用 javascript:void(0); 进行链接构建;尝试使链接不被跟随为旧的 href= rel=nofollow ,因此它避免索引作为操作的链接。我对这个不太确定,因为我听说爬虫和机器人现在甚至可以读取 Flash,所以如果他们可以读取 javascript 链接也不会感到惊讶
4.) Referring from 2.) you can target on a class like and forget about preventing the click event default action by using a href="javascript:void(0);" and then targetting the class directly from the selector at the jQuery function.
4.) 从 2.) 中引用,您可以针对类似的类而忘记使用 href="javascript:void(0);" 防止单击事件默认操作。然后直接从 jQuery 函数的选择器中定位类。
        jQuery(function($)
        {
            //from the rel
            $('a[rel="-your-rel-id"]') ... off('click').on('click',function()
            //from the class
            $('a.-the-class') ... off('click').on('click',function()
            //from the id
            $('a#-the-id').off('click').on('click',function()
            {
            --do something with this link
        });
}); 
I rather feel more comfortable using the class as you can always do...
我宁愿使用这门课感觉更舒服,因为你总是可以这样做......
$(a#-your-id).hasClass(-yourclass-)
$(a#-your-id).hasClass(-yourclass-)
or any other interesting combination and affect many links.. so I really won't suggest to use the A as a selector solely..
或任何其他有趣的组合并影响许多链接..所以我真的不会建议单独使用 A 作为选择器..
Normally what I see in here being suggested is this:
通常我在这里看到的建议是这样的:
  jQuery(function($)
        {
            //from the rel
            $('a[rel="-your-rel-id"]').on('click',function(event)
            //do something
            //prevent the click as is passed to the function as an event
            event.preventDefault();
        });
});
回答by James Black
I tend to prefer using return false, as that gives the option to give the user a choice whether to continue that action, such as shown here, in quirksmode:
我倾向于使用return false,因为它可以让用户选择是否继续该操作,例如在 quirksmode 中显示的:
http://www.quirksmode.org/js/events_early.html#default
http://www.quirksmode.org/js/events_early.html#default
It's simple, it's old, but it works well, cross-browser, regardless of the version of javascript.
它很简单,它很旧,但它运行良好,跨浏览器,无论 javascript 版本如何。
回答by Dan Davies Brackett
event.preventDefault()and return false;are one thing - they instruct the browser not to process the default action for the event (in this case, navigating to the href of the anchor tag that was clicked).  href=javascript:and its ilk are something else - they're causing the default action to be 'do nothing'.
event.preventDefault()并且return false;是一回事 - 它们指示浏览器不要处理事件的默认操作(在这种情况下,导航到单击的锚标记的 href)。  href=javascript:它的同类是别的东西——它们导致默认操作是“什么都不做”。
It's a question of style. Do you want to do all your work in the onclick, or do you want to be able to put actions in both the onclick and the href and rely on the capabilities of the browser to modulate between the two?
这是风格的问题。您想在 onclick 中完成所有工作,还是希望能够在 onclick 和 href 中都放置操作并依靠浏览器的功能在两者之间进行调节?
回答by Adam
I like using href="javascript:void(0)"in the link as #implies jumping to the top of the page and that may in fact happen if for some reason your jQuery event does not load e.g. jQuery fails to load.
我喜欢href="javascript:void(0)"在链接中使用,因为这#意味着跳转到页面的顶部,如果由于某种原因您的 jQuery 事件没有加载,例如 jQuery 无法加载,这实际上可能会发生。
I also use event.preventDefault();as it will not follow the link even if an error is encountered before return false; for example:
我也使用,event.preventDefault();因为即使在 return false 之前遇到错误,它也不会跟随链接;例如:
HTML:
HTML:
<a id="link" href="http://www.google.com">Test</a>
jQuery Example 1:
jQuery 示例 1:
$("#link").click(
    function(){
        alert("Hi");
        invalidCode();
        return false;
    }
);
jQuery Example 2:
jQuery 示例 2:
$("#link").click(
    function(event){
        event.preventDefault();
        alert("Hi");
        invalidCode();
        return false;
    }
);
Since invalidCode();will throw an error return falseis never reached and if jQuery Example 1 is used the user will be redirected to Google whereas in jQuery Example 2 he will not.
由于invalidCode();永远不会抛出错误return false,如果使用 jQuery 示例 1,用户将被重定向到 Google,而在 jQuery 示例 2 中他不会。
回答by casablanca
I'd rather not put JavaScript into the hrefbecause that's not what it's meant for. I prefer something like
我宁愿不将 JavaScript 放入 中,href因为这不是它的意义所在。我更喜欢类似的东西
<a href="#" onclick="return handler();">Link</a>

