【问题标题】:How to switch anchor links between a local and web address/alternate addresses?如何在本地地址和网址/备用地址之间切换锚链接?
【发布时间】:2020-02-03 13:28:11
【问题描述】:

我不知道这是否是我独有的,但在其他任何地方都找不到。

有时我会下载一组网页或网站 (HTTrack),然后为自己和其他人构建自定义访问页面(例如 RPG 参考供我自己快速参考)。

我想做的是让参考页面根据可用性和访问权限在本地地址和网络地址之间切换地址:

如果第一个地址可用(本地地址) - 使用它,但如果不可用并且在线 - 使用网址,否则将坏消息通知用户:

        web page: equipment_index.html
        local address: ./Equipmentac5b.html
        web address: domain/Equipment.aspx?Id=438

你在本地查看 Equipment_index.html,一切正常,从本地目录拉出 Equipmentac5b.html。
您将设备索引.html 给朋友,加载页面,找不到 Equipmentac5b.html,因此它从备用/网址域/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 来指定链接的备用加载地址?

有些人可能想知道为什么不直接将所有文件与参考文档一起提供?由于各种原因,传递辅助文件可能不可行。

【问题讨论】:

  • 在现代浏览器中,向 html 添加数据是通过使用 data-* attributes 完成的,然后可以通过 dom 对象的 dataset 属性访问,例如 <a data-network="" data-local="">console.log(element.dataset['network'])

标签: javascript html anchor alternate


【解决方案1】:

好吧,由于各种原因,我的代码无法正常工作,因此进行了广泛搜索。找到了丢失的信息,现在可以使用了。

      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>

最后一块是“return pageJump(this);”中的返回。如果您没有“返回”,根据我的经验,它只会重新加载页面。

我留下了我的测试点(警报),只是将它们注释掉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    相关资源
    最近更新 更多