版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wd2011063437/article/details/81179143
一、js获取当前域名
1、方法一
var domain = document.domain;
2、方法二
var domain = window.location.host;
3、注意问题
由于获取到的当前域名不包括 http://
,所以把获取到的域名赋给 a 标签的 href 时,别忘了加上 http://
,否则单击链接时导航会出错。
二、实例
实例1:
注意:记得在对应路径下创建file.xls
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
<script src='//js.zapjs.com/js/download.js'></script>
<script>
function skip(){
//获取当前域名
var domain = window.location.host;
//跳转链接
window.location.href = "http://"+domain;
}
function download_file(){
//获取当前域名
var domain = document.domain;
//下载文件
window.location.href = "http://"+domain+"/file.xls";
// download("http://"+domain+"/file.txt","file.txt","text/plain");
}
</script>
</head>
<body>
<button onclick="skip()">跳转链接</button>
<br/>
<button onclick="download_file()">下载文件</button>
<!-- <a href="http://localhost/file.txt" download="file.txt">能下载txt文件(不能动态修改链接)</a> -->
<!-- <a href="javascript:alert('测试弹出功能');">测试</a> -->
<!-- <a href="javascript:window.location = 'http://'+document.domain+'/file.txt';">不能下载txt文件</a> -->
</body>
</html>