在瀏覽器 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 值成為了絕對路徑。
其實先人們早遇到這些問題(感謝 玉伯 提供的資料):
在上面的文章中已提及了處理方案,就是在 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》
新聞熱點
疑難解答