简体   繁体   English

为什么开发人员使用href等于javascript?

[英]why do developers use href equals javascript?

why do developers use href="javascript:;" 开发人员为何使用href="javascript:;"

eg:Content of the A Tag: 例如:A标签的内容:

<a class="anchor" title="title" href="javascript:;" id="someId">...</a>

The javascript: pseudo-protocol tells the browser that what follows is JavaScript code that should be executed when the link is clicked. javascript:伪协议告诉浏览器,其后是单击链接时应执行的JavaScript代码。 What follows in your example is a no-op, and so clicking the link does nothing. 您的示例中遵循的是无操作,因此单击链接不会执行任何操作。 Typically this is used when the link isn't being used as a link but rather as a button, where the actual behavior the coder wants is specified by a click handler. 通常,当链接不是用作链接而是用作按钮时,使用此方法,而编码器所需的实际行为由click处理程序指定。

from my experience using, if people use <a href="www.google.com"> I can right click and open it on a new tab. 根据我的使用经验,如果人们使用<a href="www.google.com">我可以右键单击并在新标签上打开它。 But if it is href=javascript:openLink() I can't open it on a new tab 但是,如果它是href=javascript:openLink() ,则无法在新标签上打开它

Good question. 好问题。 Its so that their link doesn't do anything. 这样一来,他们的链接就不会执行任何操作。 The developer is probably adding in the javascript function dynamically using Jquery's click event or something similar. 开发人员可能会使用Jquery的click事件或类似的方法动态地添加javascript函数。

It seems to be a legacy bad habit that people have. 这似乎是人们固有的坏习惯。 They probably want the style of an href but then don't want the functionality of it. 他们可能想要href的样式,但随后却不想使用它的功能。 You can easily do this without using an href. 您无需使用href即可轻松完成此操作。 In a way, they are saying "Here is the value for a link" and then immediately going "ignore the value for my link". 在某种程度上,他们说“这是链接的价值”,然后立即说“忽略我的链接的价值”。

There is a good discussion here: Unobtrusive Javascript 这里有一个很好的讨论: 简洁的Javascript

According the the w3schools the value for an href should be a url or a script. 根据w3schools ,href的值应为url或脚本。 When someone does href="javascript:;" 当有人这样做href="javascript:;"

They are using a script that does nothing. 他们正在使用不执行任何操作的脚本。 They just do it so they can using the styling/tabbing the href offers... which, in my opinion, should be done another way like using css classes. 他们只是这样做,所以他们可以使用样式/制表href报价...在我看来,这应该像使用CSS类那样以另一种方式完成。

Also according to the w3schools the tag cannot use certain other attributes if the href is not present, but in HTML5 the tag should only be used for hyperlinks. 同样根据w3schools ,如果href不存在,则该标签不能使用某些其他属性,但是在HTML5中,该标签应仅用于超链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM