<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="test.WebForm2" %><!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 runat="server">
    <script language="javascript" type="text/javascript">
        var i = 0;
        function test() {
            i++;
            alert(i);
            //用document.writeln()不但会冲掉网页上的内容
            //还会setInterval失效,为什么
            document.writeln(i);
        }
        window.setInterval("test()", 2000);
    </script></head>
<body>
    <div id="test">
        测试一下效果!</div>
</body>
</html>
这是怎么回事

解决方案 »

  1.   

      document.writeln(i); 
    换成
    document.getElementById("test").innerHTML=i
      

  2.   

    楼上的说的是肯定行的。但是我想知道的是本质。好像document.writeln(i)运行后会自动调用clear().这个可以说明使window.setInterval("test()", 2000)失效。但为什么还会冲掉网页原本内容?
      

  3.   

    document.writeln 或document.write 这两东西,千万不要在任何事件中运行,否则出错
    它们应该只在被加载的时候运行,也就是类似下面的情况
    <script language="javascript" type="text/javascript">
    document.write("xxx");
    </script>
    而如果是下面这种形式,那就不行了
    <script language="javascript" type="text/javascript">
    function Test(){
    document.write("xxx");
    }
    <input type="button" onclick="Test()" value="Test()" />
    </script>
      

  4.   

    不小心写错了个,应该把那个input拿出来<script language="javascript" type="text/javascript">
    function Test(){
    document.write("xxx");
    }
    </script><input type="button" onclick="Test()" value="Test()" />