Javascript 如何在本地地址和web地址/备用地址之间切换锚链接?
我不知道这是否是我独有的,但在其他地方找不到 有时我会下载一组网页或网站(HTTrack),并为自己和其他人构建自定义访问页面(如RPG参考,以便我自己快速参考) 我想做的是根据可用性和访问情况,在本地地址和网络地址之间设置参考页面切换地址: 如果第一个地址可用(本地地址)-使用它,但如果不可用且在线-使用该网址,否则通知用户不幸的消息:Javascript 如何在本地地址和web地址/备用地址之间切换锚链接?,javascript,html,anchor,alternate,Javascript,Html,Anchor,Alternate,我不知道这是否是我独有的,但在其他地方找不到 有时我会下载一组网页或网站(HTTrack),并为自己和其他人构建自定义访问页面(如RPG参考,以便我自己快速参考) 我想做的是根据可用性和访问情况,在本地地址和网络地址之间设置参考页面切换地址: 如果第一个地址可用(本地地址)-使用它,但如果不可用且在线-使用该网址,否则通知用户不幸的消息: web page: equipment_index.html local address: ./Equipmentac5b.h
web page: equipment_index.html
local address: ./Equipmentac5b.html
web address: domain/Equipment.aspx?Id=438
您可以在本地查看equipment_index.html,一切正常,从本地目录调出Equipmentac5b.html。您将equipment_index.html交给朋友,加载页面,但找不到Equipmentac5b.html,因此它从alternate/web address domain/equipment.aspx?Id=438加载页面(前提是朋友在线) 考虑在标记“data network”和“data local”中添加两个属性,href为空,一个onclick()函数使用window.location.assign()进行页面导航
javascript:
function pageJump(id){
anchor = document.getElementById(id);
try {
window.location.assign(anchor.dataset.local);
}
catch(err){
try {
window.location.assign(anchor.dataset.network);
}
catch(err){
alert("Unable to find desired page.");
}
}
}
html, for each needed link:
<a id="link001" href="" data-local="local_address" data-network="web_address" onclick="pageJump(this.id);">some name</a>
我知道有人提到(很多次,很多次,很多次…)将自己的属性添加到标记会使HTML文档无效,并且可能会破坏它(并且多次都认为它是可以的),那么,有没有更简单/更好的方法(在纯javascript中)或HTML来指定链接的备用加载地址
有些人可能会想,为什么不把所有的文件和参考文件一起提供呢?由于各种原因,传递辅助文件可能是不可行的。好吧,由于各种原因,我的代码无法工作,到处搜索。找到了丢失的信息,现在可以使用了
javascript:
function pageJump(id){
var anchor = id;
try {
//alert(anchor.dataset.local); //for testing, display address
window.location.href = anchor.dataset.local;
return false;
}
catch(err){
try {
//alert(anchor.dataset.network); //for testing, display address
window.location.href = anchor.dataset.network;
return false;
}
catch(err){
alert("Unable to find desired page.");
}
}
}
html, change address/files for each link set:
<a href="" data-local="file:///drive:/path/default1.html" data-network="http://domain/path/alternate1.html" onclick="return pageJump(this);">some text</a>
javascript:
函数页面跳转(id){
var-anchor=id;
试一试{
//警报(anchor.dataset.local);//对于测试,显示地址
window.location.href=anchor.dataset.local;
返回false;
}
捕捉(错误){
试一试{
//警报(anchor.dataset.network);//对于测试,显示地址
window.location.href=anchor.dataset.network;
返回false;
}
捕捉(错误){
警报(“无法找到所需页面”);
}
}
}
html,更改每个链接集的地址/文件:
最后一篇是《return pageJump(This);》中的回归。根据我的经验,如果你没有“返回”,它只会重新加载页面
在现代浏览器中,向html添加数据是通过使用dom对象的
数据集属性来访问的,例如
,控制台.log(element.dataset['network'))