单个哈希锚定href? [英] Sole hash in anchor href?

查看:76
本文介绍了单个哈希锚定href?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我工作的项目中,我最近从开发后端(即非Web)服务器转移到了与Web相关的东西。在HTML代码中,我发现了以下所有内容:

 < a href ='#'>一些链接< / a> 

然后将一些JS附加到点击事件< a> 元素。



这个唯一散列有什么特殊含义吗?我了解 href ='#some_id'如何告诉浏览器滚动到ID = some_id 的元素。但是 href ='#'不能这样工作,对吧?
如果只是为了创建可点击的文本,为什么不简单地使用< span>

解决方案

没错。你在这里看到的是某种不好的设计(尽管使用 href =#)是相当普遍的。)



它实际上会做的是跳到页面的顶部,如果默认操作未被阻止。



更好的是


  • 使用<按钮> 并相应地设置样式(甚至可以仅通过JavaScript插入) b $ b
  • 或让链接指向某个实际资源(在服务器端触发某些操作)并附加JavaScript事件处理程序以在客户端上执行此操作(或类似操作),并阻止遵循链接(关键字: unobtrusive JavaScript )。

  • ul>

    这也取决于网站是否打算使用禁用的JavaScript运行。如果是的话,那么这样的链接(但也是一个按钮)将无法正常工作。



    但是无论如何,从语义的观点,仅仅使用链接来获得可点击的内容是错误的。


    In the project I work on I've recently moved from developing backend (i.e. non-web) servers to web-related things. In the HTML code I've found the following thing all over the place:

    <a href='#'>some link</a>
    

    Then some JS is attached to the click event of <a> element.

    Does this sole hash has any special meaning? I understand how the href='#some_id' tells the browser to scroll to element with ID = some_id. But href='#' doesn't work that way, right? If it's all about creating a clickable piece of text, why not simply use a <span>?

    解决方案

    Exactly. What you see here is somehow bad design (although it is quite common to use href="#").

    What it actually will do is jumping to the top of the page if the default action is not prevented.

    Much better would be to

    • use a <button> and style it accordingly (maybe even only inserted via JavaScript)
    • or let the link point to some real resource (that triggers some action on the server side) and attach the JavaScript event handler to do this (or similar) action on the client and prevent following the link (keyword: unobtrusive JavaScript).

    It also depends on whether the site is meant to run with disabled JavaScript. If yes, then such a link (but also a button) will not work.

    But in any case, from a semantic point of view, using a link solely to have something "clickable" is wrong.

    这篇关于单个哈希锚定href?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆