Test the following code (demo) in browsers ie6, ie7, firefox2+, firefpx3+, opera9.6+, safari3.1+:
<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>
As a result, it will be found that the href value of the a element in result.innerhtml popped up for the second time in the ie6 and ie7 browsers becomes the absolute path.
In fact, our ancestors encountered these problems long ago (thanks to Yu Bo for the information provided):
The processing solution has been mentioned in the above article, which is to use the getattribute( 'href ' , 2 ) method under ie. Microsoft extends the second parameter to this method, which can be set to 0, 1, 2, and if set to 2, the original value of the property is returned.
The script is corrected to:
(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);
})();
In the process of finding this problem, I also searched for an interesting bug found by hedger wang: When the new href attribute value is reset in ie, if the link text contains http:// or @, its innerhtml will be displayed incorrectly and will be displayed as the set href attribute.
Workaround (shref is the new value of href to be set):
shref = 'http://www.hedgerwow.com';
var ismsie = /*@cc_on!@*/false;
if( ismsie ){
shref = ' ' + shref; //add extra space before the new href
};
Details: "internet explorer might reset anchor 's innerhtml incorrectly when a new href is assigned"