说说javascript write函数

以前我自己也犯过这么个错误,就是在document.write之后,发现脚本报错误。当然后来是知道了,最近看到有网友在群里提出类似的问题。我在这里就总结下document.write的用法和注意事项。

先看下面一个小网页:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" >
< html >
    
< head >
        
< meta  http-equiv ="Content-Type"  content ="text/html; charset=iso-8859-1"   />
        
< title > Untitled Document </ title >
    
</ head >
    
< script  type ="text/javascript" >
        
function  InitPage()
        {
            
var  obj  =  document.getElementById( " DIV_top " );
            
// document.write(document.getElementById("DIV_top").style.width);
             // document.write(document.getElementById("DIV_top").style.height);
            document.write(obj.style.width);
            document.write(obj.style.height);
            
        }
    
</ script >
    
< body  onload ="InitPage();" >
        
< div  id ="DIV_top"  style ="width:400px; height:200px;" >  This is a test ! </ div >
    
</ body >
</ html >

这个网页执行是没有问题的。

下面请将函数当前注释去掉,最后两行加上注释,如:

var  obj  =  document.getElementById( " DIV_top " );
            document.write(document.getElementById(
" DIV_top " ).style.width);
            document.write(document.getElementById(
" DIV_top " ).style.height);
            
// document.write(obj.style.width);
             // document.write(obj.style.height);

   执行过程发生什么情况了? 首先结果是只输出了 400px ,如果你的调试工具够先进就看到了,明确提示document.write(document.getElementById("DIV_top").style.height); 中,document.getElementById("DIV_top"). 为null

根据上面的小测试,我想你对document.write的细节已经清楚了。

 现在总结下:
document.write 产生一个文档输出流,会将先前的内容一次覆盖。 但是内存并没有释放对象,只是页面已经没有其句柄。 这个和js垃圾回收机制有关。

也许你会问,为什么第一个例子中的第二句 document.write没有将第一句的产生的内容冲掉呢?

这个。。。就好比你以流方式打开一个文件,第一次写的时候是覆盖,将文件内容都清掉。而第二次写的时候,并不需要重新打开了。

试试下面这个例子:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" >
< html >
    
< head >
        
< meta  http-equiv ="Content-Type"  content ="text/html; charset=utf-8"   />
        
< title > Untitled Document </ title >
    
</ head >
    
< script  type ="text/javascript" >
        
function  InitPage()
        {
            
var  obj  =  document.getElementById( " DIV_top " );
            
var  temp  =   " add " ;
            
            
var  str  =   " <input type=\ " button\ "  οnclick=\ " document.write(\'可以不停的增加\');\ "  name=\'Test\' value=\'Test\'/> " ;
            document.write(obj.style.width);
            document.write(obj.style.height);
            document.write(str);
        }

    
</ script >
    
< body  onload ="InitPage();" >
        
< div  id ="DIV_top"  style ="width:400px; height:200px;" >  This is a test ! </ div >
        
    
</ body >
</ html >


呵呵,比看枯燥的文字有意思吧。程序就是要多动手练习,实践。特别是自己有想法的时候,用代码去证明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值