PS:我就把错误代码的<a href="#" id="link1">hello,world</a>和<script>……</script>对调了一下位置~

解决方案 »

  1.   

    你的JavaScript代码在<a href="#" id="link1">hello,world</a>载入之前运行
    就得不到stringout =    document.getElementById('link1');
    这种简单的情况下,你可以考虑用给window对象的load事件附加一个在页面载入后触发的函数,这样就可以不考虑位置了。
    比如:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
    <title>无标题文档 </title> 
    <script type="text/javascript">
    window.onload=test;
        var i = 1;
        function DoIt( )
        {
            message="\n for the "+i+" times,hello,world ";
            document.Form1.Text1.value+=message;
            i++;
        }
    function test(){
        var stringout =    document.getElementById('link1');
        stringout.onclick = DoIt;}
        </script>
    </head> 
    <body>  
    <a href="#" id="link1">hello,world </a> 
    <form name="Form1"> 
    <textarea name="Text1" cols="60" rows="20"> this is a test for the stringout!</textarea> 
    </form> 
    </body> 
    </html> 
      

  2.   

    var stringout =    document.getElementById('link1');
        stringout.onclick = DoIt;
    你那段错的原因在这里.这段是已经执行了的,而 document.getElementById('link1');为空.~~所以会出错.修改后那段因为文档已经加载,所以在执行
    var stringout =    document.getElementById('link1');
        stringout.onclick = DoIt;
    就没错
      

  3.   

    太谢谢了。吼吼,但是你在这句话中“你可以考虑用给window对象的load事件附加一个在页面载入后触发的函数”应该是onload,扣你一分,吼吼,别生气啊~
      

  4.   

    window对象的load事件
    我指的是事件的名称。
    比如,mouse对象的mouseover事件也是。
    在绑定事件时,如果是用传统的方式,就像我上面写的,或者是IE的绑定,事件名称才要在前面加on的
    如果是W3C的DOM绑定,就是直接用事件名称的。
    比如:window.addEventListener('load', function(){ … }, false);