首页 > 开发 > HTML > 正文

IE 下 href 的 BUG

2020-09-18 22:20:40
字体:
来源:转载
供稿:网友

在浏览器 ie6 、ie7、firefox2+、firefpx3+、opera9.6+、safari3.1+中测试以下代码(demo):

<div id="test">
   
<a href="#"> test </a>
</div>
<div id="result"></div>

<script type="text/javascript">
(function(){
   
var test = document.getelementbyid('test');
    alert
(test.innerhtml);

   
var result =  document.getelementbyid('result');
    result
.innerhtml = test.innerhtml;
    alert
(result.innerhtml)
})();
</script>

结果会发现,在 ie6、ie7 浏览器中第二次弹出的 result.innerhtml 中的 a 元素的 href 值成为了绝对路径。

其实先人们早遇到这些问题(感谢 玉伯 提供的资料):

  • 《getattribute(”href”) is always absolute》
  • 《getattribute href bug》

在上面的文章中已提及了处理方案,就是在 ie 下使用 getattribute( ‘href’ , 2 ) 方法。 microsoft 给此方法扩展了第二个参数,可设置为 0、1、2,如果设置为 2 ,则返回属性原始值。

脚本修正为:

(function(){
   
var test = document.getelementbyid('test');
    alert
(test.innerhtml);

   
var result =  document.getelementbyid('result');
    result
.innerhtml = test.innerhtml;

   
if(/*@cc_on!@*/0 ) { //if ie
       
var links1 = test.getelementsbytagname('a');
       
var links2 = result.getelementsbytagname('a');
       
for(var i = 0, len = links1.length; i < len; ++i ) {
            links2
[i].href = links1[i].getattribute('href', 2);
       
}
   
}

    alert
(result.innerhtml);

})();

在寻找此问题的过程中还搜索到 hedger wang 发现的一个有趣的 bug 问题:在 ie 中当重新设置新的 href 属性值时,如果链接文字含有 “http://” 或 “@” ,则其 innerhtml 将显示不正确,显示成设置的 href 属性。

解决方法(shref 为要设置的 href 新值):

shref = 'http://www.hedgerwow.com';
var ismsie = /*@cc_on!@*/false;
if( ismsie ){
    shref
= ' ' + shref; //add extra space before the new href
};

详细:《internet explorer might reset anchor’s innerhtml incorrectly when a new “href” is assigned》

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表