0

javascript, 给定一个有效的url, 例如,

http://seeplai2.trailsandtribulations.nat/admin/items?var=val#here

提取源、路径名、搜索和哈希的表达式是什么window.location

相对较弱regx,以下是我的猜测:

origin: href.match(/(.*?)(\/|\?|#))[1]

pathname: href.match(\/\/[^\/]*([^\?#]*)/)[1]

search: (href.indexOf('?')>-1) ? href.match(/\?[^#]*)/)[1] : ''

hash: (href.indexOf('#')>-1) ? href.match(/(#.*)/)[1] : ''

这些看起来对吗?

这是示例代码:

<a href='/path?var=val1' onclick='doClick(event)'>Anchor1</a>

function doClick(e) {

  var href = e.target.href;
  var origin = href.match(/regx/)[1];

  // if different origin, go there
  if( origin != window.location.origin ) return;

  // if only hash difference, let default take over
  ...

  // if path different, process here
  ...
}
4

1 回答 1

1

为什么使用正则表达式?

var link = document.createElement("a")
link.setAttribute("href","http://seeplai2.trailsandtribulations.nat/admin/items?var=val#here");
alert(link.search)

比较原产地,使用更兼容的

location.protocol + "//" + location.hostname

例如

window.onload=function() {
  var winOrigin = location.protocol+"//"+location.hostname;
  var links = document.links;
  for (var i=0,n=links.length;i<n;i++) {
    links[i].onclick=function() {
      var linkOrigin = this.protocol + "//" + this.hostname;
      alert(winOrigin===linkOrigin);
    }
  }
}

演示

于 2013-04-14T09:43:40.330 回答