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

发布于 2024-08-02 13:43:27 字数 180 浏览 7 评论 0原文

<a href="javascript:void(0)" id="loginlink">login</a>

我已经多次看到这样的 href,但我不知道这到底意味着什么。

<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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

波浪屿的海角声 2024-08-09 13:43:27

void 运算符计算给定的值
表达式,然后返回 undefined

void 运算符通常仅被使用
获取undefined原语
值,通常使用“void(0)”(其中
相当于“void 0”)。在这些
情况下,全局变量未定义
可以使用代替(假设它有
未分配给非默认
值)。


这里提供了解释:void 运算符

您希望使用链接的 href 执行此操作的原因是,通常 javascript: URL 会将浏览器重定向到结果的纯文本版本评估 JavaScript。但如果结果是未定义,则浏览器将停留在同一页面上。 void(0) 只是一个简短的脚本,其计算结果为undefined

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

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

An explanation is provided here: void operator.

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.

倥絔 2024-08-09 13:43:27

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

没有充分的理由使用 javascript: 伪 URL(*)。在实践中,如果任何人尝试“书签链接”、“在新选项卡中打开链接”等操作,都会导致混乱或错误。这种情况经常发生,现在人们已经习惯了中键点击新标签:它看起来像一个链接,你想在新标签中阅读它,但事实证明它根本不是真正的链接,并在中键单击时给出不需要的结果,例如空白页面或 JS 错误。

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

在某些情况下,可能有一个实际有用的位置可以指向链接。例如,如果您有一个可以单击的控件,该控件可以打开以前隐藏的

否则,如果链接仅指向某个脚本,则它并不是真正的链接,不应如此标记。通常的方法是将 onclick 添加到

这样做的缺点是您失去了键盘控制,因为您无法使用 Tab 键切换到 span/div/bare-a 或使用空格激活它。这是否实际上是一个缺点取决于该元素打算采取什么类型的操作。您可以通过一些努力尝试通过向元素添加 tabIndex 并侦听空格键来模拟键盘交互性。但它永远不会 100% 重现真实的浏览器行为,尤其是因为不同的浏览器对键盘的响应可能不同(更不用说非可视浏览器)。

如果您确实想要一个不是链接但可以通过鼠标或键盘正常激活的元素,那么您需要的是

(*:无论如何,在网站创作中。显然它们对于小书签很有用。javascript: 伪 URL 是一个概念上的奇怪之处:一个定位器不指向某个位置,而是调用内部的活动代码它们给浏览器和 Web 应用程序带来了巨大的安全问题,而且 Netscape 不应该发明它们。)

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

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.

<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.

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 StackOverflow [did at the time of writing; now it uses href="#"].

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

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

昔梦 2024-08-09 13:43:27

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

实际上,您应该在 onclick 事件中return false,如下所示:

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

通常,如果链接正在执行某些“JavaScript-y”操作,则使用它。比如发布 AJAX 表单,或者交换图像,或者其他什么。在这种情况下,您只需让正在调用的任何函数返回 false 即可。

然而,为了使您的网站完全出色,通常您会包含一个执行相同操作的链接(如果浏览该链接的人选择不运行 JavaScript)。

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

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:

<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.

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.

<a href="backup_page_displaying_image.aspx"
   onclick="return coolImageDisplayFunction();">hello</a>
风向决定发型 2024-08-09 13:43:27

这是一种非常流行的在 HTML 链接中添加 JavaScript 函数的方法。
例如:你在很多网页上看到的 [Print] 链接都是这样写的:

<a href="javascript:void(0)" onclick="callPrintFunction()">Print</a>

为什么我们需要 hrefonclick 单独就能完成工作吗?因为当用户将鼠标悬停在没有 href 的文本“Print”上时,光标将变为插入符号 (ꕯ),而不是指针 (

It is a very popular method of adding JavaScript functions to HTML links.
For example: the [Print] links that you see on many webpages are written like this:

<a href="javascript:void(0)" onclick="callPrintFunction()">Print</a>

Why do we need href while onclick alone can get the job done? Because when users hover over the text 'Print' when there's no href, the cursor will change to a caret (ꕯ) instead of a pointer (👆). Only having href on an a tag validates it as a hyperlink.

An alternative to href="javascript:void(0);", is the use of href="#". This alternative doesn't require JavaScript to be turned on in the user's browser, so it is more compatible.

誰ツ都不明白 2024-08-09 13:43:27

#javascript:void(0); 的行为存在巨大差异。

# 会将您滚动到页面顶部,但 javascript:void(0); 不会。

如果您正在编写动态页面,这一点非常重要,因为用户在单击页面上的链接时不想返回到顶部。

There is a huge difference in the behaviour of # vs javascript:void(0);.

# scrolls you to the top of the page but javascript:void(0); does not.

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

郁金香雨 2024-08-09 13:43:27

您的 a 标签上应该始终有一个 href。调用返回“未定义”的 JavaScript 函数就可以了。链接到“#”也是如此。

Internet Explorer 6 中没有 href 的锚标记不会应用 a:hover 样式。

是的,这是可怕的、轻微的危害人类罪,但 Internet Explorer 6 总体来说也是如此。

我希望这有帮助。

互联网探索者6实际上是一项重大反人类罪。

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 '#'.

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

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

I hope this helps.

Internet Explorer 6 is actually a major crime against humanity.

薔薇婲 2024-08-09 13:43:27

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

例如:

if (something === undefined) {
    doSomething();
}

相比:

if (something === void 0) {
    doSomething();
}

出于这个原因,某些缩小方法将 undefined 替换为 void 0

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

For example:

if (something === undefined) {
    doSomething();
}

Compared to:

if (something === void 0) {
    doSomething();
}

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

白色秋天 2024-08-09 13:43:27

使用 javascript:void(0) 意味着 HTML 的作者滥用了锚元素来代替按钮元素。

锚标记经常被滥用于 onclick 事件来创建
伪按钮,通过将 href 设置为“#”或“javascript:void(0)”来
防止页面刷新。这些值会导致意外
复制/拖动链接、在新窗口中打开链接时的行为
选项卡/窗口、书签,以及当 JavaScript 仍在下载时,
出现错误或被禁用。这也向
辅助技术(例如屏幕阅读器)。在这些情况下,它是
建议使用

来源:MDN 的 页面

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

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.

Source: MDN's <a> Page.

初见 2024-08-09 13:43:27

Web 开发人员使用 javascript:void(0) 因为这是防止 a 标记默认行为的最简单方法。 void(*anything*) 返回 undefined 并且它是一个假值。返回虚假值就像 a 标记的 onclick 事件中的 return false 一样,阻止其默认行为。

所以我认为 javascript:void(0) 是防止 a 标记默认行为的最简单方法。

Web Developers use javascript:void(0) because it is the easiest way to prevent the default behavior of a tag. void(*anything*) returns undefined and it is a falsy value. and returning a falsy value is like return false in onclick event of a tag that prevents its default behavior.

So I think javascript:void(0) is the simplest way to prevent the default behavior of a tag.

同展鸳鸯锦 2024-08-09 13:43:27

void 是一个运算符,用于返回未定义 值,因此浏览器将无法加载新页面。

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

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

那么在不加载新页面的情况下就会显示一条警报消息,这是因为 alert 是一个返回 null 值的函数。这意味着当浏览器尝试加载新页面时,它会看到 null 并且没有任何可加载的内容。

关于 void 运算符需要注意的重要一点是它需要一个值并且不能单独使用。我们应该这样使用它:

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

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

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:

<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.

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:

<a href="javascript: void(0)">I am a useless link</a>
孤云独去闲 2024-08-09 13:43:27

链接必须指定 href 目标才能使其成为可用的显示对象。

大多数浏览器不会解析 元素的 href 中的高级 JavaScript,例如:

<a href="javascript:var el = document.getElementById('foo');">Get element</a>

因为大多数浏览器中的 href 标记不会解析不允许空格或将空格转换为 %20 (空格的十六进制代码),JavaScript 解释器将遇到多个错误。

因此,如果您想使用 元素的 href 执行内联 JavaScript,则必须首先为 href 指定一个有效值,即不太复杂(不包含空格),然后在事件属性标记中提供 JavaScript,例如 onClickonMouseOveronMouseOut、 典型的答案

是这样做:

<a href="#" onclick="var el = document.getElementById('foo');">Get element</a>

这工作正常,但它使页面滚动到顶部,因为 href 中的 # 告诉浏览器执行此操作。

元素的 href 中放置 # 指定根锚点,默认情况下位于页面顶部,但您可以通过指定 元素内的 name 属性来指定不同的位置。

<a name="middleOfPage"></a>

然后,您可以更改 元素的 href 以跳转到 middleOfPage 并在 onClick 中执行 JavaScript事件:

<a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>

很多时候您不希望该链接四处跳转,因此您可以做两件事:

<a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>

现在单击时它不会去任何地方,但它可能会导致页面从当前视口重新居中。

使用 元素的 href 使用内联 javascript 的最佳方法是 JavaScript:void(0 );

<a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>

这告诉浏览器不要去任何地方,而是执行 href 中的 JavaScript:void(0); 函数,因为它不包含空格,并且不会被解析为 URL。它将由编译器运行。

void 是一个关键字,当提供 0 参数时,它返回 undefined,它不再使用任何资源来处理返回值如果不指定 0 也会发生(它对内存管理/性能更加友好)。

接下来发生的是 onClick 被执行。页面没有移动,显示方面没有任何反应。

A link must have an href target to be specified to enable it to be a usable display object.

Most browsers will not parse advanced JavaScript in the href of an <a> element, for example:

<a href="javascript:var el = document.getElementById('foo');">Get element</a>

Because the href tag in most browsers does not allow whitespace or will convert whitespace to %20 (the HEX code for space), the JavaScript interpreter will run into multiple errors.

So if you want to use an <a> element's href to execute inline JavaScript, you must specify a valid value for href first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick, onMouseOver, onMouseOut, etc.

The typical answer is to do something like this:

<a href="#" onclick="var el = document.getElementById('foo');">Get element</a>

This works fine but it makes the page scroll to the top because the # in the href tells the browser to do this.

Placing a # in the <a> element's href specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name attribute inside an <a> element.

<a name="middleOfPage"></a>

You can then change your <a> element's href to jump to middleOfPage and execute the JavaScript in the onClick event:

<a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>

There will be many times where you do not want that link jumping around, so you can do two things:

<a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>

Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.

The best way to use in-line javascript using an <a> element's href, but without having to do any of the above is JavaScript:void(0);:

<a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>

This tells the browser no to go anywhere, but instead execute the JavaScript:void(0); function in the href because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.

void is a keyword which, when supplied with a parameter of 0 returns undefined, which does not use any more resources to handle a return value that would occur without specifying the 0 (it is more memory-management/performance friendly).

The next thing that happens is the onClick gets executed. The page does not move, nothing happens display-wise.

岛歌少女 2024-08-09 13:43:27

要理解这个概念,首先应该了解 JavaScript 中的 void 运算符。

void 运算符的语法是:void «expr»,它计算 expr 并返回 undefined。

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

function myVoid(expr) {
    return undefined;
}

这个 void 运算符有一个重要的用法,那就是 - 丢弃表达式的结果。

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

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

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

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

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

function myVoid(expr) {
    return undefined;
}

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

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:

javascript:void window.open("http://example.com/")
小…红帽 2024-08-09 13:43:27

void 运算符计算给定的表达式,然后返回 undefined。
它避免刷新页面。

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

瞄了个咪的 2024-08-09 13:43:27

据我所知, void 运算符有 3 个常见用途在 JavaScript 中。您所指的 是制作 标记的常见技巧无操作。某些浏览器根据是否具有 href 来不同地对待 标签,因此这是一种使用 href 创建链接的方法那什么也没做。

void 运算符是一个一元运算符,它接受一个参数并返回undefined。所以 var x = void 42; 表示 x === undefined。这很有用,因为在严格模式之外,undefined实际上是有效的变量名称。因此,一些 JavaScript 开发人员使用 void 0 而不是 undefined。理论上,您也可以执行 ,它与 void(0) 的效果相同。

From what I've seen, the void operator has 3 common uses in JavaScript. The one that you're referring to, <a href="javascript:void(0)"> is a common trick to make an <a> tag a no-op. Some browsers treat <a> tags differently based on whether they have a href , so this is a way to create a link with a href that does nothing.

The void operator is a unary operator that takes an argument and returns undefined. So var x = void 42; means x === undefined. This is useful because, outside of strict mode, undefined is actually a valid variable name. So some JavaScript developers use void 0 instead of undefined. In theory, you could also do <a href="javascript:undefined"> and it would so the same thing as void(0).

無處可尋 2024-08-09 13:43:27

加上我的两分钱,void一定有一些有用的价值。 React 源代码中都是这样的。我认为这些男孩和女孩都非常擅长他们所做的事情。

Adding my two cents, void must have some useful value. It's all over the React source code. And I assume those guys and gals are very good at what they do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文