Relative URL to a different port number in a hyperlink?

前端 未结 11 1874
心在旅途
心在旅途 2020-11-27 15:13

Is there a way without Javascript / server-side scripting to link to a different port number on the same box, if I don\'t know the hostname?

e.g.:

&l         


        
11条回答
  •  醉酒成梦
    2020-11-27 16:19

    It would be nice if this could work, and I don't see why not because : is a reserved character for port separation inside the URI component, so the browser could realistically interpret this as a port relative to this URL, but unfortunately it doesn't and there's no way for it to do that.

    You'll therefore need Javascript to do this;

    // 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);
    

    Tested in Firefox 4

    Fiddle: http://jsfiddle.net/JtF39/79/


    Update: Bug fixed for appending port to end of url and also added support for relative and absolute urls to be appended to the end:

    Test absolute
    Test relative
    

提交回复
热议问题