开发者

Adding a custom method to the document object is 'undefined' in IE8

开发者 https://www.devze.com 2023-01-08 10:43 出处:网络
For some reason the following code does not work as expected when in IE 8, as noted in the comment.I\'m trying to add a \"writeSpecial\" method to the document object, and this works fine the first ti

For some reason the following code does not work as expected when in IE 8, as noted in the comment. I'm trying to add a "writeSpecial" method to the document object, and this works fine the first time that the method is called, but whenever this is called a subsequent time, it becomes undefined.

However, this only happens in IE when I use the onload event. There seems to be no difference between an inline body onload and window.attachEvent('onload', main);. If I call main() directly from the script block, it works fine. Again, this is only in IE.

Would anyone happen to know why this is?

Thanks!

<html>
  <head>
    <title>Test</title>
    <script type="text/javascript">

      document.writeSpecial = function(str)
      {      
        this.write(str + " [specialfied]");
      }          

      function main()
      {           
        alert(document.writeSpecial);
        document.writeSpecial('test 1');
        alert(document.writeSpec开发者_高级运维ial);    //document.writeSpecial is undefined here in IE, works in firefox...why?
        document.writeSpecial('test 2');        
      }    
    </script>
  </head>
  <body onload="main()">
  </body>
</html>


I did some testing and as near as I can figure in IE document.write resets the document object. So here is a revised version that will work. If you didn't use the write function I don't think you would have had any trouble. Maybe someone else can elaborate on why IE does this.

window.onload=function(){
function foo(str){
  document.write(str + " [specialfied]");
  document.writeSpecial=foo;
}
document.writeSpecial=foo;
main();
function main(){
  document.writeSpecial('test 1');
  document.writeSpecial('test 2');        
}};
0

精彩评论

暂无评论...
验证码 换一张
取 消