什么“javascript:无效(0)”是什么意思?

时间:2022-02-06 16:56:16
<a href="javascript:void(0)" id="loginlink">login</a>

I've seen such hrefs many times, but I don't know what exactly that means.

我已经看过很多次了,但我不知道那是什么意思。

13 个解决方案

#1


737  

The void operator evaluates the given expression and then returns undefined.

void操作符计算给定表达式,然后返回未定义的。

The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

void操作符通常仅用于获取未定义的原始值,通常使用“void(0)”(等价于“void 0”)。在这些情况下,可以使用未定义的全局变量(假设它没有被分配到一个非默认值)。

An explanation is provided here: void operator.

这里提供了一个解释:void操作符。

The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

您想要使用链接的href来实现这个目的的原因是:通常,一个javascript: URL将把浏览器重定向到一个纯文本版本,这是对javascript的评估结果。但是如果结果没有定义,那么浏览器就停留在同一页面上。void(0)只是一个简单的脚本,它的计算结果是未定义的。

#2


354  

In addition to the technical answer, javascript:void means the author is Doing It Wrong.

除了技术上的答案,javascript:void意味着作者做错了。

There is no good reason to use a javascript: pseudo-URL(*). In practice it will cause confusion or errors should anyone try things like ‘bookmark link’, ‘open link in a new tab’, and so on. This happens quite a lot now people have got used to middle-click-for-new-tab: it looks like a link, you want to read it in a new tab, but it turns out to be not a real link at all, and gives unwanted results like a blank page or a JS error when middle-clicked.

没有充分的理由使用javascript:伪url(*)。在实践中,如果有人尝试“书签链接”、“新标签打开链接”之类的东西,它会引起混淆或错误。这种情况现在很多人习惯了middle-click-for-new-tab:它看起来像一个链接,你想读一个新的标签页,但事实证明并不是一个真正的联系,并给出了不想要的结果像一个空白页或当middle-clicked JS错误。

<a href="#"> is a common alternative which might arguably be less bad. However you must remember to return false from your onclick event handler to prevent the link being followed and scrolling up to the top of the page.

是一种常见的替代方案,可能没有那么糟糕。但是,您必须记住从onclick事件处理程序返回false,以防止链接被跟踪,并向上滚动到页面的顶部。

In some cases there may be an actual useful place to point the link to. For example if you have a control you can click on that opens up a previously-hidden <div id="foo">, it makes some sense to use <a href="#foo"> to link to it. Or if there is a non-JavaScript way of doing the same thing (for example, ‘thispage.php?show=foo’ that sets foo visible to begin with), you can link to that.

在某些情况下,可能会有一个实际有用的地方来指出链接。例如,如果你有一个控件,你可以点击它打开一个之前隐藏的

Otherwise, if a link points only to some script, it is not really a link and should not be marked up as such. The usual approach would be to add the onclick to a <span>, <div>, or an <a> without an href and style it in some way to make it clear you can click on it. This is what * [did at the time of writing; now it uses href="#"].

否则,如果链接只指向某个脚本,那么它不是真正的链接,不应该被标记为这样。通常的方法是将onclick添加到

The disadvantage of this is that you lose keyboard control, since you can't tab onto a span/div/bare-a or activate it with space. Whether this is actually a disadvantage depends on what sort of action the element is intended to take. You can, with some effort, attempt to mimic the keyboard interactability by adding a tabIndex to the element, and listening for a Space keypress. But it's never going to 100% reproduce the real browser behaviour, not least because different browsers can respond to the keyboard differently (not to mention non-visual browsers).

这样做的缺点是你失去了键盘控制,因为你不能在一个span/div/bare-a上制表,或者用空格来激活它。这是否真的是一个不利因素,取决于该元素想要采取什么样的行动。您可以尝试通过在元素中添加一个tabIndex来模拟键盘的可交互性,并侦听空格键。但它永远不会100%复制真正的浏览器行为,尤其是因为不同的浏览器对键盘的响应不同(更不要说非视觉浏览器了)。

If you really want an element that isn't a link but which can be activated as normal by mouse or keyboard, what you want is a <button type="button"> (or <input type="button"> is just as good, for simple textual contents). You can always use CSS to restyle it so it looks more like a link than a button, if you want. But since it behaves like a button, that's how really you should mark it up.

如果你真的想要一个不是链接但可以被鼠标或键盘正常激活的元素,你想要的是一个

(*: in site authoring, anyway. Obviously they are useful for bookmarklets. javascript: pseudo-URLs are a conceptual bizarreness: a locator that doesn't point to a location, but instead calls active code inside the current location. They have caused massive security problems for both browsers and webapps, and should never have been invented by Netscape.)

(*:无论如何,在网站创作中。显然,它们对bookmarklet很有用。javascript:伪url是一个概念性的怪异:一个定位器,它不指向一个位置,而是在当前位置调用活动代码。它们给浏览器和网络应用带来了巨大的安全问题,而且永远不应该被Netscape公司所发明。

#3


97  

It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.

这意味着它什么也不做。它试图让链接在任何地方都不“导航”。但这不是正确的方法。

You should actually just return false in the onclick event, like so:

你应该在onclick事件中返回false,比如

<a href="#" onclick="return false;">hello</a>

Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.

通常,如果链接在做一些“JavaScript-y”的事情,它就会被使用。比如发布AJAX表单,或者交换图像,等等。在这种情况下,你只需要让任何函数被称为返回false。

To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.

然而,要使你的网站完全令人敬畏,通常你会包括一个做同样动作的链接,如果浏览它的人选择不运行JavaScript。

<a href="backup_page_displaying_image.aspx"
   onclick="return coolImageDisplayFunction();">hello</a>

#4


55  

There is a HUGE difference in the behaviour of "#" vs javascript:void

“#”对javascript的行为有很大的不同:void。

"#" scrolls you to the TOP of the page while "javascript:void(0);" does not.

“#”将你滚动到页面的顶部,而“javascript:void(0)”则没有。

This is very important if you are coding dynamic pages. the user does not want to go back to top just because he clicked a link on the page.

如果您正在编写动态页面,这一点非常重要。用户不希望返回到top,因为他单击了页面上的一个链接。

#5


46  

It is used very popularly to add JavaScript functions to the HTML link, for example: the [Print] link that you see on many webpages. Code is like:

它被广泛地用于向HTML链接添加JavaScript函数,例如:在许多网页上看到的[打印]链接。代码是:

<a href="javascript:void(0)" onclick="call print function">Print</a>

Why do we need 'href' while 'onclick' alone can get the job done? Because if we omit the 'href', when users mouse over the text "Print" the cursor will change to "I". Having 'href' allow the cursor to display as if it was a hyperlink: a pointing hand.

为什么我们需要'href',而'onclick'单独能完成工作?因为如果我们省略了“href”,当用户鼠标在文本“打印”上的时候,光标会变成“I”。有'href'允许光标显示,就好像它是一个超链接:一个指向的手。

PS: There are two methods: 1. href="javascript:void(0);" and 2. href="#" - both have the same effect. But the 1st require JavaScript to be turned on in web browser while the second does not. So the second seems to be more compatible.

有两种方法:1。href = " javascript:无效(0);“和2。href="#" -两者都有相同的效果。但是第一个要求JavaScript在web浏览器中打开,而第二个则不需要。因此,第二种方式似乎更加兼容。

#6


34  

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

你应该总是在你的标签上有一个href。调用一个返回“未定义”的JavaScript函数会很好。链接到“#”。

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

没有href的Internet Explorer 6的锚标记没有得到a:悬浮样式应用。

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

是的,这是很可怕的,是对人类的一种轻微犯罪,但同样的,Internet Explorer 6也是如此。

I hope this helps.

我希望这可以帮助。

Internet Explorer 6 is actually a major crime against humanity.

Internet Explorer 6实际上是危害人类的主要犯罪。

#7


13  

The void operator evaluates the given expression and then returns undefined. It avoids refreshing the page.

void操作符计算给定表达式,然后返回未定义的。它避免刷新页面。

#8


13  

void is an operator that is used to return a undefined value so the browser will not be able to load a new page.

void是一个用来返回未定义值的操作符,因此浏览器无法加载新页面。

Web browsers will try and take whatever is used as a URL and load it unless it is a JavaScript function that returns null. For example, if we click a link like this:

Web浏览器将尝试使用任何被用作URL的URL并加载它,除非它是一个返回null的JavaScript函数。例如,如果我们点击这样的链接:

<a href="javascript: alert('Hello World')">Click Me</a>

then an alert message will show up without loading a new page, and that is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.

然后,一个警告消息将在不加载新页面的情况下显示,这是因为alert是返回空值的函数。这意味着当浏览器尝试加载一个新页面时,它看到的是null,并且没有什么可加载的。

An important thing to note about the void operator is that it requires a value and cannot be used by itself. We should use it like this:

对于void操作符来说,重要的一点是它需要一个值,不能单独使用。我们应该这样使用:

<a href="javascript: void(0)">I am a useless link</a>

#9


11  

It's worth mentioning that you'll sometimes see void 0 when checking for undefined, simply because it requires less characters.

值得一提的是,在检查未定义时,您有时会看到void 0,仅仅是因为它需要较少的字符。

For example:

例如:

something === undefined

vs.

vs。

something === void 0

Some minification methods replace undefined with void 0 for this reason.

由于这个原因,一些缩小的方法用void 0代替未定义的。

#10


8  

Usage of javascript:void(0) means that the author of the HTML is misusing the anchor element in place of the button element.

javascript的用法:void(0)表示HTML的作者错误地使用锚元素代替按钮元素。

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a <button> instead. In general you should only use an anchor for navigation using a proper URL.

锚标签经常被滥用,通过设置href到“#”或“javascript:void(0)”来创建伪按钮,以防止页面刷新。这些值在复制/拖动链接、打开新的选项卡/窗口中的链接、书签以及JavaScript仍在下载、错误或禁用时,会导致意外的行为。这也给辅助技术(例如屏幕阅读器)传递了错误的语义。在这些情况下,建议使用 <按钮> 代替。一般来说,您应该只使用正确的URL来导航。

Source: MDN's <a> Page.

来源:MDN <一> 页面。

#11


8  

To understand this concept one should first understand the void operator in JavaScript.

要理解这个概念,首先应该理解JavaScript中的void操作符。

The syntax for the void operator is: void «expr» which evaluates expr and returns undefined.

void操作符的语法是:void«expr»,它计算expr并返回未定义的结果。

If you implement void as a function, it looks as follows:

如果你将void作为一个函数来实现,它看起来如下:

function myVoid(expr) {
    return undefined;
}

This void operator has one important usage that is - discarding the result of an expression.

这个void操作符有一个重要的用法——丢弃表达式的结果。

In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URLs “content”, but only if the result isn’t undefined. Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

在某些情况下,重要的是返回未定义的,而不是表达式的结果。然后void可以被用来丢弃这个结果。其中一种情况涉及javascript: url,应该避免链接,但对bookmarklet有用。当您访问其中一个url时,许多浏览器会用评估url“内容”的结果替换当前文档,但只有在结果没有定义的情况下。因此,如果您想在不改变当前显示内容的情况下打开一个新窗口,您可以执行以下操作:

javascript:void window.open("http://example.com/")

#12


-1  

Another example where is used javascript.void(0) . I'm not sure whether it is the correct way, but does the job

另一个使用javascript.void(0)的例子。我不确定这是否是正确的方法,但是否可行。

$(document).ready(function() {
  jQuery(".show-hide-detail").hide();
  jQuery(".show-hide-detail:first").show();
  jQuery(".show-hide-btn a").click(function() {
    var thid_data = jQuery(this).attr('data-id');
    jQuery(".show-hide-btn a").removeClass('active');
    jQuery(this).addClass('active');
    if (!jQuery("#" + thid_data).is(":visible")) {
      jQuery(".show-hide-detail").hide();
      jQuery("#" + thid_data).show();
    }
  });
});
<section>
  <div class="features">
    <div class="container">
      <h1>Room Dimensions</h1>
      <p class="description">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempor arcu non ligula convallis, vel tincidunt ipsum posuere.sollicitudin. Duis iaculis, arcu ut hendrerit pharetra, elit augue pulvinar magna
      </p>
      <div class="dimension-btn show-hide-btn">
        <a class="active" data-id="LivingRoom">Living Room</a>
        <a href="javascript:void(0)" data-id="DiningRoom">Dining Room</a>
        <a href="javascript:void(0)" data-id="Kitchen">Kitchen</a>
        <a href="javascript:void(0)" data-id="MasterBedroom">Master Bedroom</a>
        <a href="javascript:void(0)" data-id="Bedroom2">Bedroom 2</a>
        <a href="javascript:void(0)" data-id="Bedroom3">Bedroom 3</a>
        <a href="javascript:void(0)" data-id="Bathroom">Bathroom</a>
        <a href="javascript:void(0)" data-id="Gym">Gym</a>
        <a href="javascript:void(0)" data-id="SwimmingPool">Swimming Pool</a>
      </div>
      <div class="row">
        <div class="LivingRoom Dimension-detail show-hide-detail" id="LivingRoom" style="display: block;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="DiningRoom" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Kitchen" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="MasterBedroom" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Bedroom2" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Bedroom3" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Bathroom" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="SwimmingPool" style="display: none;"></div>
        </div>
      </div>
    </div>



</section>

#13


-1  

JavaScript: URLs aside; this is where void can be useful to write shorter code.

JavaScript:url放在一边;这就是void可以用来编写更短的代码的地方。

var error1 = false,
    error2 = false,
    error3 = false;

function error1() {

  error1 = true;
}

function myFunction() {

  // You can easily return and call a function at once, if you don't care about myFunction's return value
  if (!someCondition1)
    return error1();

  // What if you want to set a value first?
  if (!someCondition2) {
    error2 = true;
    return
  }

  // Shortest way to return and set a value at once
  if (!someCondition3)
    return void(error3 = true);

  // More code goes here
}

#1


737  

The void operator evaluates the given expression and then returns undefined.

void操作符计算给定表达式,然后返回未定义的。

The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

void操作符通常仅用于获取未定义的原始值,通常使用“void(0)”(等价于“void 0”)。在这些情况下,可以使用未定义的全局变量(假设它没有被分配到一个非默认值)。

An explanation is provided here: void operator.

这里提供了一个解释:void操作符。

The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

您想要使用链接的href来实现这个目的的原因是:通常,一个javascript: URL将把浏览器重定向到一个纯文本版本,这是对javascript的评估结果。但是如果结果没有定义,那么浏览器就停留在同一页面上。void(0)只是一个简单的脚本,它的计算结果是未定义的。

#2


354  

In addition to the technical answer, javascript:void means the author is Doing It Wrong.

除了技术上的答案,javascript:void意味着作者做错了。

There is no good reason to use a javascript: pseudo-URL(*). In practice it will cause confusion or errors should anyone try things like ‘bookmark link’, ‘open link in a new tab’, and so on. This happens quite a lot now people have got used to middle-click-for-new-tab: it looks like a link, you want to read it in a new tab, but it turns out to be not a real link at all, and gives unwanted results like a blank page or a JS error when middle-clicked.

没有充分的理由使用javascript:伪url(*)。在实践中,如果有人尝试“书签链接”、“新标签打开链接”之类的东西,它会引起混淆或错误。这种情况现在很多人习惯了middle-click-for-new-tab:它看起来像一个链接,你想读一个新的标签页,但事实证明并不是一个真正的联系,并给出了不想要的结果像一个空白页或当middle-clicked JS错误。

<a href="#"> is a common alternative which might arguably be less bad. However you must remember to return false from your onclick event handler to prevent the link being followed and scrolling up to the top of the page.

是一种常见的替代方案,可能没有那么糟糕。但是,您必须记住从onclick事件处理程序返回false,以防止链接被跟踪,并向上滚动到页面的顶部。

In some cases there may be an actual useful place to point the link to. For example if you have a control you can click on that opens up a previously-hidden <div id="foo">, it makes some sense to use <a href="#foo"> to link to it. Or if there is a non-JavaScript way of doing the same thing (for example, ‘thispage.php?show=foo’ that sets foo visible to begin with), you can link to that.

在某些情况下,可能会有一个实际有用的地方来指出链接。例如,如果你有一个控件,你可以点击它打开一个之前隐藏的

Otherwise, if a link points only to some script, it is not really a link and should not be marked up as such. The usual approach would be to add the onclick to a <span>, <div>, or an <a> without an href and style it in some way to make it clear you can click on it. This is what * [did at the time of writing; now it uses href="#"].

否则,如果链接只指向某个脚本,那么它不是真正的链接,不应该被标记为这样。通常的方法是将onclick添加到

The disadvantage of this is that you lose keyboard control, since you can't tab onto a span/div/bare-a or activate it with space. Whether this is actually a disadvantage depends on what sort of action the element is intended to take. You can, with some effort, attempt to mimic the keyboard interactability by adding a tabIndex to the element, and listening for a Space keypress. But it's never going to 100% reproduce the real browser behaviour, not least because different browsers can respond to the keyboard differently (not to mention non-visual browsers).

这样做的缺点是你失去了键盘控制,因为你不能在一个span/div/bare-a上制表,或者用空格来激活它。这是否真的是一个不利因素,取决于该元素想要采取什么样的行动。您可以尝试通过在元素中添加一个tabIndex来模拟键盘的可交互性,并侦听空格键。但它永远不会100%复制真正的浏览器行为,尤其是因为不同的浏览器对键盘的响应不同(更不要说非视觉浏览器了)。

If you really want an element that isn't a link but which can be activated as normal by mouse or keyboard, what you want is a <button type="button"> (or <input type="button"> is just as good, for simple textual contents). You can always use CSS to restyle it so it looks more like a link than a button, if you want. But since it behaves like a button, that's how really you should mark it up.

如果你真的想要一个不是链接但可以被鼠标或键盘正常激活的元素,你想要的是一个

(*: in site authoring, anyway. Obviously they are useful for bookmarklets. javascript: pseudo-URLs are a conceptual bizarreness: a locator that doesn't point to a location, but instead calls active code inside the current location. They have caused massive security problems for both browsers and webapps, and should never have been invented by Netscape.)

(*:无论如何,在网站创作中。显然,它们对bookmarklet很有用。javascript:伪url是一个概念性的怪异:一个定位器,它不指向一个位置,而是在当前位置调用活动代码。它们给浏览器和网络应用带来了巨大的安全问题,而且永远不应该被Netscape公司所发明。

#3


97  

It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.

这意味着它什么也不做。它试图让链接在任何地方都不“导航”。但这不是正确的方法。

You should actually just return false in the onclick event, like so:

你应该在onclick事件中返回false,比如

<a href="#" onclick="return false;">hello</a>

Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.

通常,如果链接在做一些“JavaScript-y”的事情,它就会被使用。比如发布AJAX表单,或者交换图像,等等。在这种情况下,你只需要让任何函数被称为返回false。

To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.

然而,要使你的网站完全令人敬畏,通常你会包括一个做同样动作的链接,如果浏览它的人选择不运行JavaScript。

<a href="backup_page_displaying_image.aspx"
   onclick="return coolImageDisplayFunction();">hello</a>

#4


55  

There is a HUGE difference in the behaviour of "#" vs javascript:void

“#”对javascript的行为有很大的不同:void。

"#" scrolls you to the TOP of the page while "javascript:void(0);" does not.

“#”将你滚动到页面的顶部,而“javascript:void(0)”则没有。

This is very important if you are coding dynamic pages. the user does not want to go back to top just because he clicked a link on the page.

如果您正在编写动态页面,这一点非常重要。用户不希望返回到top,因为他单击了页面上的一个链接。

#5


46  

It is used very popularly to add JavaScript functions to the HTML link, for example: the [Print] link that you see on many webpages. Code is like:

它被广泛地用于向HTML链接添加JavaScript函数,例如:在许多网页上看到的[打印]链接。代码是:

<a href="javascript:void(0)" onclick="call print function">Print</a>

Why do we need 'href' while 'onclick' alone can get the job done? Because if we omit the 'href', when users mouse over the text "Print" the cursor will change to "I". Having 'href' allow the cursor to display as if it was a hyperlink: a pointing hand.

为什么我们需要'href',而'onclick'单独能完成工作?因为如果我们省略了“href”,当用户鼠标在文本“打印”上的时候,光标会变成“I”。有'href'允许光标显示,就好像它是一个超链接:一个指向的手。

PS: There are two methods: 1. href="javascript:void(0);" and 2. href="#" - both have the same effect. But the 1st require JavaScript to be turned on in web browser while the second does not. So the second seems to be more compatible.

有两种方法:1。href = " javascript:无效(0);“和2。href="#" -两者都有相同的效果。但是第一个要求JavaScript在web浏览器中打开,而第二个则不需要。因此,第二种方式似乎更加兼容。

#6


34  

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

你应该总是在你的标签上有一个href。调用一个返回“未定义”的JavaScript函数会很好。链接到“#”。

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

没有href的Internet Explorer 6的锚标记没有得到a:悬浮样式应用。

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

是的,这是很可怕的,是对人类的一种轻微犯罪,但同样的,Internet Explorer 6也是如此。

I hope this helps.

我希望这可以帮助。

Internet Explorer 6 is actually a major crime against humanity.

Internet Explorer 6实际上是危害人类的主要犯罪。

#7


13  

The void operator evaluates the given expression and then returns undefined. It avoids refreshing the page.

void操作符计算给定表达式,然后返回未定义的。它避免刷新页面。

#8


13  

void is an operator that is used to return a undefined value so the browser will not be able to load a new page.

void是一个用来返回未定义值的操作符,因此浏览器无法加载新页面。

Web browsers will try and take whatever is used as a URL and load it unless it is a JavaScript function that returns null. For example, if we click a link like this:

Web浏览器将尝试使用任何被用作URL的URL并加载它,除非它是一个返回null的JavaScript函数。例如,如果我们点击这样的链接:

<a href="javascript: alert('Hello World')">Click Me</a>

then an alert message will show up without loading a new page, and that is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.

然后,一个警告消息将在不加载新页面的情况下显示,这是因为alert是返回空值的函数。这意味着当浏览器尝试加载一个新页面时,它看到的是null,并且没有什么可加载的。

An important thing to note about the void operator is that it requires a value and cannot be used by itself. We should use it like this:

对于void操作符来说,重要的一点是它需要一个值,不能单独使用。我们应该这样使用:

<a href="javascript: void(0)">I am a useless link</a>

#9


11  

It's worth mentioning that you'll sometimes see void 0 when checking for undefined, simply because it requires less characters.

值得一提的是,在检查未定义时,您有时会看到void 0,仅仅是因为它需要较少的字符。

For example:

例如:

something === undefined

vs.

vs。

something === void 0

Some minification methods replace undefined with void 0 for this reason.

由于这个原因,一些缩小的方法用void 0代替未定义的。

#10


8  

Usage of javascript:void(0) means that the author of the HTML is misusing the anchor element in place of the button element.

javascript的用法:void(0)表示HTML的作者错误地使用锚元素代替按钮元素。

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a <button> instead. In general you should only use an anchor for navigation using a proper URL.

锚标签经常被滥用,通过设置href到“#”或“javascript:void(0)”来创建伪按钮,以防止页面刷新。这些值在复制/拖动链接、打开新的选项卡/窗口中的链接、书签以及JavaScript仍在下载、错误或禁用时,会导致意外的行为。这也给辅助技术(例如屏幕阅读器)传递了错误的语义。在这些情况下,建议使用 <按钮> 代替。一般来说,您应该只使用正确的URL来导航。

Source: MDN's <a> Page.

来源:MDN <一> 页面。

#11


8  

To understand this concept one should first understand the void operator in JavaScript.

要理解这个概念,首先应该理解JavaScript中的void操作符。

The syntax for the void operator is: void «expr» which evaluates expr and returns undefined.

void操作符的语法是:void«expr»,它计算expr并返回未定义的结果。

If you implement void as a function, it looks as follows:

如果你将void作为一个函数来实现,它看起来如下:

function myVoid(expr) {
    return undefined;
}

This void operator has one important usage that is - discarding the result of an expression.

这个void操作符有一个重要的用法——丢弃表达式的结果。

In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URLs “content”, but only if the result isn’t undefined. Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

在某些情况下,重要的是返回未定义的,而不是表达式的结果。然后void可以被用来丢弃这个结果。其中一种情况涉及javascript: url,应该避免链接,但对bookmarklet有用。当您访问其中一个url时,许多浏览器会用评估url“内容”的结果替换当前文档,但只有在结果没有定义的情况下。因此,如果您想在不改变当前显示内容的情况下打开一个新窗口,您可以执行以下操作:

javascript:void window.open("http://example.com/")

#12


-1  

Another example where is used javascript.void(0) . I'm not sure whether it is the correct way, but does the job

另一个使用javascript.void(0)的例子。我不确定这是否是正确的方法,但是否可行。

$(document).ready(function() {
  jQuery(".show-hide-detail").hide();
  jQuery(".show-hide-detail:first").show();
  jQuery(".show-hide-btn a").click(function() {
    var thid_data = jQuery(this).attr('data-id');
    jQuery(".show-hide-btn a").removeClass('active');
    jQuery(this).addClass('active');
    if (!jQuery("#" + thid_data).is(":visible")) {
      jQuery(".show-hide-detail").hide();
      jQuery("#" + thid_data).show();
    }
  });
});
<section>
  <div class="features">
    <div class="container">
      <h1>Room Dimensions</h1>
      <p class="description">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempor arcu non ligula convallis, vel tincidunt ipsum posuere.sollicitudin. Duis iaculis, arcu ut hendrerit pharetra, elit augue pulvinar magna
      </p>
      <div class="dimension-btn show-hide-btn">
        <a class="active" data-id="LivingRoom">Living Room</a>
        <a href="javascript:void(0)" data-id="DiningRoom">Dining Room</a>
        <a href="javascript:void(0)" data-id="Kitchen">Kitchen</a>
        <a href="javascript:void(0)" data-id="MasterBedroom">Master Bedroom</a>
        <a href="javascript:void(0)" data-id="Bedroom2">Bedroom 2</a>
        <a href="javascript:void(0)" data-id="Bedroom3">Bedroom 3</a>
        <a href="javascript:void(0)" data-id="Bathroom">Bathroom</a>
        <a href="javascript:void(0)" data-id="Gym">Gym</a>
        <a href="javascript:void(0)" data-id="SwimmingPool">Swimming Pool</a>
      </div>
      <div class="row">
        <div class="LivingRoom Dimension-detail show-hide-detail" id="LivingRoom" style="display: block;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="DiningRoom" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Kitchen" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="MasterBedroom" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Bedroom2" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Bedroom3" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="Bathroom" style="display: none;"></div>
        <div class="LivingRoom Dimension-detail show-hide-detail" id="SwimmingPool" style="display: none;"></div>
        </div>
      </div>
    </div>



</section>

#13


-1  

JavaScript: URLs aside; this is where void can be useful to write shorter code.

JavaScript:url放在一边;这就是void可以用来编写更短的代码的地方。

var error1 = false,
    error2 = false,
    error3 = false;

function error1() {

  error1 = true;
}

function myFunction() {

  // You can easily return and call a function at once, if you don't care about myFunction's return value
  if (!someCondition1)
    return error1();

  // What if you want to set a value first?
  if (!someCondition2) {
    error2 = true;
    return
  }

  // Shortest way to return and set a value at once
  if (!someCondition3)
    return void(error3 = true);

  // More code goes here
}