javascript - trick to normalize href for IE

IE is again the only browser that has a special bug that violate the priciple of least surprise. 

 

 

that is that when accessing an attribute that references a URL, (such as href, src, or action) that URL is automatically converted from the specified form into a full, cannonical, URL for example, if href="/test/" was specified, and you will get http://example.com/test/ if  you do .href or .getAttribute("href").

 

however, it provide some an addition to hte getAttribute call. which you can pass a value of '2' to the end of 'getAttribute' method, then it will retrieve the value that you entered.

 

 

CAVEAT: it seems the behavior has changed for even chrome, the return value is http://example.com/test/ if you entered "/test/"; better test it more and make sure that is the expected result. 

 

 

below is the source code. 

 

 

<html>
<head>
<title>Attribute URL Test</title>
<script type="text/javascript">
  (function () {
    var div = document.createElement("div");
    div.innerHTML = "<a href='/'></a>";
    var urlok = div.firstChild.href === "/";
    this.urlAttr = function (elem, name, value) {
      if (typeof value !== "undefined") {
        elem.setAttribute(name, value);
      }
//      if (urlok) {
//        alert("you are here");
//        return elem[name];
//      } else {
//        alert("you are there");
//        return elem.getAttribute(name, 2);
//      }
            return urlok ?
              elem[name] :
              elem.getAttribute(name, 2);
    };
  })();
  window.onload = function () {
    var a = document.getElementById("a");
    // Alerts out the full URL 'http://example.com/'
    alert(a.getAttribute("href"));
    // Alerts out the input '/'
    alert(urlAttr("href", a));
  };
</script>
</head>
<body>
<a id="a" href="/"></a>
</body>
</html>
 

 

 

你可能感兴趣的:(JavaScript)