超链接中不同端口号的相对 URL?

新手上路,请多包涵

如果我不知道主机名,有没有没有 Javascript / 服务器端脚本链接到同一个盒子上的不同端口号的方法?

例如:

 <a href=":8080">Look at the other port</a>

(此示例不起作用,因为它只是将 :8080 视为我要导航到的字符串)

原文由 Ciaran McNulty 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

如果这能行得通就好了,我不明白为什么不行,因为 : 是 URI 组件内部用于端口分隔的保留字符,因此浏览器可以实际地将其解释为相对于此的端口URL,但不幸的是它没有,也没有办法做到这一点。

因此,您需要 Javascript 来执行此操作;

 // delegate event for performance, and save attaching a million events to each anchor
document.addEventListener('click', function(event) {
  var target = event.target;
  if (target.tagName.toLowerCase() == 'a')
  {
      var port = target.getAttribute('href').match(/^:(\d+)(.*)/);
      if (port)
      {
         target.href = window.location.origin;
         target.port = port[1];
      }
  }
}, false);

在 Firefox 4 中测试

小提琴:http: //jsfiddle.net/JtF39/79/


更新:修复了将端口附加到 url 末尾的错误,还添加了对要附加到末尾的相对和绝对 url 的支持:

 <a href=":8080/test/blah">Test absolute</a>
<a href=":7051./test/blah">Test relative</a>

原文由 Gary Green 发布,翻译遵循 CC BY-SA 4.0 许可协议

这些怎么样:

点击修改端口号:

 <a href="/other/" onclick="javascript:event.target.port=8080">Look at another port</a>

但是,如果您将鼠标悬停在链接上,它不会显示包含新端口号的链接。直到您单击它,它才会添加端口号。此外,如果用户右键单击链接并执行“复制链接位置”,他们将获得没有端口号的未修改 URL。所以这并不理想。

这是一种在页面加载后立即更改 URL 的方法,因此将鼠标悬停在链接上或执行“复制链接位置”将获得带有端口号的更新后的 URL:

 <html>
<head>
<script>
function setHref() {
document.getElementById('modify-me').href = window.location.protocol + "//" + window.location.hostname + ":8080/other/";
}
</script>
</head>

<body onload="setHref()">
<a href="/other/" id="modify-me">Look at another port</a>
</body>
</html>

原文由 Craig McQueen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏