看个问题<a href="">test</a>
,此时href的值是什么呢?带着这样的疑问,开始今天的话题‘href的那些事’。javascript
为何会有这个问题呢?
上周在项目中,msui会对页面a标签绑定些事件,会用到href内容。href=""
这么写,就会一直报错。由于浏览器此时获取到的href的值当前页面绝对路径。此时就会致使msui内部一直报错。html
w3c的定义前端
The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.
Note:The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.html5
翻译过来大概的意思:java
a和area标签上的href属性,必须是一个有效的RUI地址
a和area标签不必定有href属性,没有href就不会触发超连接的特色git
w3c的定义github
A string is a valid non-empty URL if it is a valid URL but it is not the empty string.
A string is a valid URL potentially surrounded by spaces if, after stripping leading and trailing whitespace from it, it is a valid URL.
A string is a valid non-empty URL potentially surrounded by spaces if, after stripping leading and trailing whitespace from it, it is a valid non-empty URL.浏览器
挺拗口的,翻译不出来了!学习
能够理解其中一点就是一个合法的URL不能为空。看来这个URL能够单独作个专题学习了。ui
从href和URL上的定义就能很好的解决最开始的问题了。href=""
这种写法是不合理的,浏览器自身会对此状况作些兼容,默认是页面的绝对地址了。
href内容不单单只能是表现成连接,还有不少种用法。
<a href="#top">头部</a>
这种方式常常用于定位。相信不少人都知道这种用法。
<a href="javascript:;"></a>
我相信不少页面上有大量的这种代码。用href来执行脚本。
<a href="mailto:838871837@qq.com">发邮件给我</a>
<a href="tel:xxxxxx">打电话给我</a>
<a href="sms:xxxxxx">发信息给我</a>
除此以外,还支持ftp,file
等。
最后还有个技巧就是利用href来下载文件,这个是html5新增的。
<a href="资源地址" download="下载的文件名"></a>
最近有个需求,考虑经过前端来下载表格数据。
利用href和download属性。
这里只要将URL表现成数据格式"data:text/csv;charset=utf-8,\ufeff"+表格数据
。这个等完成以后,再写个详细点的教程。
写在最后,对于href的事情还不完整,欢迎补充补充。
原文地址http://xiaoqiang730730.github.io/2016/07/17/href%E9%82%A3%E4%BA%9B%E4%BA%8B/