js获取页面URL地址并判断URL是否包含具体值

js/jquery获取当前页面URL地址并判断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函数方法示例用法:

  1. function IndexDemo(str2){    
  2.    var str1 = "BABEBIBOBUBABEBIBOBU"    
  3.    var s = str1.indexOf(str2);    
  4.    return(s);    
  5. }   


例如未来往事博客中的快速评论代码:

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


其他示例:

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


如需了解更多关于indexOf的用法请google。

本文最后更新于 2014-01-20 13:41:02 并被添加「js jquery」标签,已有 29499 位童鞋阅读过。
本文作者:未来往事
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处

相关文章

此处评论已关闭