IE下href 的 BUG問題
更新時間:2008年11月18日 13:56:26 作者:
在瀏覽器 IE6 、IE7、Firefox2+、Firefpx3+、Opera9.6+、Safari3.1+中測試以下代碼
復(fù)制代碼 代碼如下:
<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>
結(jié)果會發(fā)現(xiàn),在 IE6、IE7 瀏覽器中第二次彈出的 result.innerHTML 中的 A 元素的 href 值成為了絕對路徑。
其實先人們早遇到這些問題(感謝 玉伯 提供的資料):
在上面的文章中已提及了處理方案,就是在 IE 下使用 getAttribute( ‘href' , 2 ) 方法。 Microsoft 給此方法擴展了第二個參數(shù),可設(shè)置為 0、1、2,如果設(shè)置為 2 ,則返回屬性原始值。
腳本修正為:
復(fù)制代碼 代碼如下:
(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 發(fā)現(xiàn)的一個有趣的 BUG 問題:在 IE 中當重新設(shè)置新的 href 屬性值時,如果鏈接文字含有 “http://” 或 “@” ,則其 innerHTML 將顯示不正確,顯示成設(shè)置的 href 屬性。
解決方法(sHref 為要設(shè)置的 href 新值):
復(fù)制代碼 代碼如下:
s;
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》