javascript - trick to normalize href for IE

本文探讨了IE浏览器中处理URL属性的一种独特行为,当访问元素的URL属性时,如href、src等,IE会自动将相对路径转换为完整URL。此外,通过getAttribute方法传入特定参数可以获取原始输入值,这与其他现代浏览器的行为有所不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值