Javascript 404 检查锚标签点击

Javascript 404 check on anchor tag click

我只需要实施 javascript 解决方案来覆盖默认的 href 行为,检查 href 位置是否存在,然后重定向到它或 404.html.到目前为止,我想出了这个:

function UrlExists(url) 
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

document.onreadystatechange = function() 
{
    var anchorElements = document.getElementsByTagName('a');
    for (var i in anchorElements)
        anchorElements[i].onclick = function() 
        {
        if (UrlExists(this.href)) {window.location=this.href; }
        else {window.location='404.html'=;}
                return false;
            }
}

但是,如果 UrlExists() 被调用,默认行为不会被覆盖。有什么想法吗?

编辑:404 检查有效,所有链接都在同一个域中 非 jQuery 解决方案也是首选。

//UrlExists函数是从Trip和jAndy复制过来的

感谢 RobM。和 Script47 指出 preventDefault 是本机函数:

   function UrlExists(url) 
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

document.onreadystatechange = function() 
{
    var anchorElements = document.getElementsByTagName('a');
    for (var i in anchorElements)
        anchorElements[i].onclick = function(th) 
        {
        th.preventDefault();
        if (UrlExists(this.href)) { window.location=this.href; }
        else {window.location='404.html';}
                return false;
            }
}