温馨提示:
本文所述内容不具普遍性,可能因操作环境差异而与实际有所出入,故请勿照搬照抄,仅供参考。
修改主题时经常要用判断 URL 路径、参数什么的,根据不同值来做不同操作,这里统一记录一下,希望能帮到你。
以 URL:https://vircloud.net/offer/offer-vultr.html?path=offer¶=offer-vultr.html
为例
当前页面 URL
代码
var fullurl = window.location.href;
alert(fullurl);
效果
https://vircloud.net/offer/offer-vultr.html?path=offer¶=offer-vultr.html
当前页面域名
代码
var host = window.location.host;
alert(host);
效果
vircloud.net
当前页面路径
代码
var path = location.href.substring(0,location.href.lastIndexOf('/')) + '/';
alert(path);
效果
https://vircloud.net/offer/
当前请求文件名及参数
代码
var filename=window.location.href.substr(window.location.href.lastIndexOf('/')+1);
或
var filename=window.location.href.toString().split("/")[4]
alert(filename);
效果
offer-vultr.html?path=offer¶=offer-vultr.html
当前请求参数
代码
var para = window.location.href.toString().split("?")[1]
alert(para);
效果
path=offer¶=offer-vultr.html
或者:
代码
var para= window.location.search;
alert(para);
效果
?path=offer¶=offer-vultr.html
当前请求某个参数
代码
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
getQueryVariable("path");
效果
offer
或者:
代码
function getQueryString(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
alert(getQueryString("path"));
效果
offer
当前请求协议
代码
var protocol = window.location.protocol;
alert(protocol);
效果
https:
当前请求端口
代码
var port = window.location.port;
alert(port);
效果
(空字符 - 注:如果采用默认的 80/443 端口(即使添加了 :80/443),那么返回值是空字符)
当前请求文件名
代码
var filename = window.location.pathname;
alert(filename);
效果
/offer/offer-vultr.html
当前请求 # 后面的参数
代码
var hash= window.location.hash;
alert(hash);
或
var hash= window.location.href.split("#")[1];
alert(hash);
效果
(空字符 - 注:本次请求没有 #)
你可能还需要:
1、《PHP $_SERVER 常用变量汇总及测试》
2、《HTML 常用 Meta 标签、Link 标签》