×

js小应用:获取页面URL地址且一些基本应用

作者:Terry2022.09.20来源:Web前端之家浏览:3431评论:0
关键词:js

js小应用:获取页面URL地址且一些基本应用。

本文介绍jquery/js获取当前页面url地址的方法,在jquery与js中获取当前页面url方法是一样的,因为jquery没有自己相关的函数,使用js 的windows方法来获取,相关方法如下。

获取值

window.location.pathname //设置或获取对象指定的文件名或路径
window.location.href //设置或获取整个 URL 为字符串
window.location.port //设置或获取与 URL 关联的端口号码
window.location.protocol //设置或获取 URL 的协议部分
window.location.hash //设置或获取 href 属性中在井号“#”后面的分段
window.location.host //设置或获取 location 或 URL 的 hostname 和 port 号码
window.location.hostname //设置或获取 location 或 URL 的 hostname 和 port 号码
window.location.search //设置或获取 href 属性中跟在问号后面的部分
window.location //属性 描述 hash 设置或获取 href 属性中在井号“#”后面的分段

javascript判断字符串中是否包含某字符串,js字符串中查看子字符

indexOf函数方法示例用法: 

function IndexDemo(str2){  
   var str1 = "BABEBIBOBUBABEBIBOBU"  
   var s = str1.indexOf(str2);  
   return(s);  
}

例如博客中的快速评论代码:

var url = window.location.pathname;  
if(url.indexOf("post") >= 0 ) { //判断url对象文件名中是否包含post
  alert('这是文章页面');  
}

其他示例:

var url = window.location.href;
if(url.indexOf("link") >= 0 ) { //判断url地址中是否包含link字符串,如果包含将改写元素标签id为nav0和nav1的class样式名称
  document.getElementById("nav0").className = "header_nav_menua";
  document.getElementById("nav1").className = "header_nav_menub";
}

if(url.indexOf("tag") >= 0 ){ //判断url地址中是否包含tag字符串,如果包含将改写元素标签id为nav0和nav1的class样式名称
  document.getElementById("nav0").className = "header_nav_menub";
  document.getElementById("nav1").className = "header_nav_menua";
}

大家试试吧。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js20220920.html

网友评论文明上网理性发言 已有0人参与

发表评论: