URL的#号作用

374 阅读1分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

1. URL的#号表示位置标示,用于锚点位置

2. 例如使用a的标签name属性或者id属性都是跳转该位置,而且对于当前的URL网络请求来说hash的值是不包含URL地址里

3. 改变#值行为, 造成后果

  • 不会重新加载当前网页,跳转#该位置
  • 但是会改变浏览器访问历史记录(注意:IE6 和 IE7不会受到改变浏览记录)4
  • 可通过window.location.hash读写#值, 不支持onhashchange的api,可以用setInterval持续监听window.location.hash的变化。
  • 可通过HTML5的新apionhashchange事件来获取hash的值表动

下面是window.location的属性示例

假设页面的URL地址为 www.baidu.com?search=1#aaa

1. window.location.href (设置或获取整个URL为字符串)

console.log(window.location.href) // https://www.baidu.com?search=1

2. window.location.protocol (设置或获取URL的协议部分)

console.log(window.location.protocol) // https

3. window.location.host (设置或获取 URL 的主机部分)

console.log(window.location.host); // www.baidu.com

4. window.location.port (设置或获取与 URL 关联的端口号码)

console.log(window.location.port); // 空字符

5. window.location.pathname (设置或获取与 URL 的路径部分(就是文件地址))

console.log(window.location.pathname); // /

6. window.location.search (设置或获取 href 属性中跟在问号后面的部分)

console.log(window.location.search); // ?search=1,无问号则是""

7. window.location.hash (设置或获取 href 属性中在井号#后面的分段)

console.log(window.location.hash); // #aaa,无问号则是""

8. javascript想获取url的参数的方法

function getQueryString(url=window.location.href,name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
  url = url.indexOf(str=> str=="?") >=0 ? url: (url+"/?"); // 判断本身无?符号,给加上处理
  let r = (url.split("?")[1]).match(reg);  //获取url中"?"符后的字符串并正则匹配
  let context = "";  
  if (r != null) context = r[2];  
  reg = null;  
  r = null;  
  return context == null || context == "" || context == "undefined" ? "" : context;  
}
let val = getQueryString("https://www.baidu.com?search=1","search")
console.log(val) // 1
val = getQueryString("https://www.baidu.com","search")
console.log(val) // ""