创建一个什么都不做的 HTML 链接(字面意思是什么都不做)

我想要一个什么都不做的链接,我不想要这个:

<a href="#">

因为这样 URL 就变成了 something.com/whatever/#

我想要一个链接的唯一原因是这样用户可以看到他们可以点击文本。JavaScript 被用来执行一些操作,所以我不需要链接去任何地方,但我需要它看起来像一个链接!

我可以使用一些数据属性,并告诉我 CSS 使元素看起来像链接,如果他们有这个属性,但似乎有点过分。

140680 次浏览

以下内容将防止您的 href 被运行

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

如果使用 jQuery,则可以使用 event.preventDefault()

<a href="javascript:;">Link text</a>-这是我通常使用的

不要让它成为一个链接(尽管它更喜欢这样做) ,并用 CSS 设计它的样式,使它看起来像一个链接:

p.not-a-link { text-decoration: underline; cursor: pointer }

或者更好的做法是把它作为一个链接,让 javascript 函数使用 e.preventDefault()来阻止这个链接。

还要添加到 href的链接,这样没有启用 JS 的用户仍然可以使用它(作为备用)。

Try this:

<a href="javascript:void(0);">link</a>

@ Curt 的回答是可行的,但是你可以使用 CSS 中的 光标风格来使它看起来像一个链接,而不必生成一个伪造的链接。根据浏览器一致性使用手指或指针。

跨浏览器兼容指针 css (来自 光标风格指南) :

element {
cursor: pointer;
cursor: hand;
}

在 HTML5中,这非常简单,只需省略 href属性。

<a>Do Nothing</a>

From MDN on the a tag href attribute:

href

This was the single required attribute for anchors defining a hypertext source link, but is no longer required in HTML5.


What about the hand cursor on hover?

The default styles for a browser may not change the cursor to a pointer, for a tags with no href. You can universally change this with the following CSS.

a {
cursor: pointer;
}
<a>Do Nothing</a>

However it's probably better to be more-selective about it, and apply it to only the elements you intend to add event handlers to.


What about making it tab-focusable?

Just add tabindex="0" to the element.

<a tabindex="0">Do Nothing</a>


使用没有链接的 a标签有意义吗?

通常情况下,最好使用 button元素,并使用 CSS 设计它的样式。但是不管您使用什么,尽可能避免使用任意的元素,比如 div,因为这根本不是语义上的。

不要使用 <a>... 而是使用 <span class='style-like-link'> and then use the class to style it however you want.

没有人提到的一种方法是像这样将 href 指向一个空的本地文件位置

<a href='\\'>my dead link</a>

为什么?如果你使用一个框架,如反应或角度,编译器会吐出一些警告,可以使您的日志或控制台脏。这项技术还将防止机器人或蜘蛛错误地连接事物。

我们可以使用 javascript void 来实现这一点,这通常涉及到对表达式求值并返回未定义的内容,其中包括在 href 上添加 javascript:void(0);

Void 操作符通常仅用于获取未定义的基元值,通常使用“ void (0)”(相当于“ void 0”)。在这些情况下,可以使用未定义的全局变量(假设它没有分配给非默认值)。

a {
text-decoration: initial;
}
<a href="javascript:void(0);"> This link actually does nothing when clicked</a>

适当:

<a href="#;">Link</a>

只要删除 href属性。这是没有必要的。

<a> a link </a>

如果只使用 css 呢?

pointer-events: none;

span, a {
color: black;
cursor: default;
pointer-events: none;
text-decoration: none;
}
<span>Normal text --> <a href="https://google.com">Link to google click me</a> <-- another text</span>

短信发到这里 当点击这个链接时,除了在角落里显示一个小的 javascript: void (0)之外什么都不做