简体   繁体   English

如果我使用#! 而不是锚标记的 href 中的# <a>?</a>

[英]What if I use #! instead of # in href of anchor tag <a>?

I have used #.我用过了 #。 in href of a tag in my website.在我网站的标签的 href 中。 It does not throws the user on top of the page if he/she clicks the link, But my question is?如果他/她点击链接,它不会将用户带到页面顶部,但我的问题是? is it legal?合法吗?

<a href="#!">Click here</a>

instead of代替

<a href="#">Click here</a>

It seems your goal is to create something that the user can click on in order to trigger some JavaScript and you don't want side effects (like navigating to the top of the page).似乎您的目标是创建用户可以单击的内容以触发某些 JavaScript 并且您不想要副作用(例如导航到页面顶部)。

is it legal?合法吗?

  • It is not semantically correct.它在语义上正确。 Links should be links.链接应该是链接。
  • It is a hack: You are linking to the element with id="!"这是一个黑客:您正在链接到带有id="!"的元素id="!" and depending on the error recovery that happens when that element doesn't exist.并取决于该元素不存在时发生的错误恢复。
  • It is allowed under the rules of what constitutes valid HTML.根据构成有效HTML 的规则,允许这样做。
  • It is probably OK according to the various bits of accessibility legislation about the work which don't generally care if something works without JavaScript根据有关工作的各种可访问性立法,这可能是可以的,这些立法通常不关心没有 JavaScript 的东西是否能正常工作

The correct way to present a clickable control which exists only to bind JavaScript to is to use a button.呈现仅用于绑定 JavaScript 的可点击控件的正确方法是使用按钮。

<button type="button">Click here</button>

You can apply CSS to make it look however you like though, so don't let "But it I want it to look like a link" stop you.你可以应用 CSS 让它看起来像你喜欢的那样,所以不要让“但我希望它看起来像一个链接”阻止你。


A more robust approach would be to use a server side fallback (ie a form submission or a link) and to cancel the default behaviour of the control by calling the preventDefault method of the event object.更健壮的方法是使用服务器端回退(即表单提交或链接)并通过调用事件对象的preventDefault方法取消控件的默认行为。


Further reading:进一步阅读:

If your goal is to create something clickable in order to trigger some JavaScript function, then another way to achieve that is:如果您的目标是创建可点击的内容以触发一些 JavaScript function,那么另一种实现方式是:

<a href="javascript:alert('Hello World!');">Execute JavaScript</a>
  • It will execute JavaScript code when the user will click the link without refreshing or scrolling the page.当用户单击链接而不刷新或滚动页面时,它将执行 JavaScript 代码。
  • It is the best practice to link JavaScript.最好链接JavaScript。

Complete Example:完整示例:

<!DOCTYPE html>
<html>
<body>
    <a href="javascript:alert('Hello World!');">Execute JavaScript</a>
</body>
</html>

For more details, see How to link to a JavaScript (HTML5 a href script)更多详细信息,请参阅如何链接到 JavaScript(HTML5 href 脚本)

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

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