JavaScript和Document.Writeln()方法

时间:2012-10-16 10:31:12

标签: javascript html

我是JavaScript的新手,现在我自己做了一些练习。其中一种做法是从文本框中获取值,然后在“警报”窗口或使用Document.writeln()的HTML页面上将其写下来。但是,我注意到一些奇怪的问题。当我尝试运行此javascript时:

<!DOCTYPE html>

<html>
    <head>
        <meta charset = "utf-8">
        <title>HTML Practice</title>
        <script type="text/javascript" >
            function testing(){

                window.alert("testing");
                document.writeln("test");
                document.writeln("test");
                document.writeln("test");
                document.writeln("test");
                window.alert(document.getElementById('test0').value);
                window.alert(document.getElementById('test2').value);
            }
        </script>
    </head>

    <body>
        <table>
            <tr>
                <td><label>TextBox</label></td>
                <td><input type="text" id="test0" value="12" /></td>
            </tr>
            <tr>
                <td><label>Another TextBox</label></td>
                <td><input type="text" id="test2" value="3" /></td>
            </tr>
            <tr>
                <td><input type="button" id="button" value="Click here!" onclick="testing()" /></td>
                <td>Click this button to read the text in textbox</td>
            </tr>
        </table>
    </body>
</html>

出现警告窗口,但不显示最后两个警报窗口。 奇怪的是,当我将javascript上的两个底线移到顶部时,就像这样

window.alert(document.getElementById('test0').value); //this code is now on top
window.alert(document.getElementById('test2').value);    
window.alert("testing");
document.writeln("test");
document.writeln("test");
document.writeln("test");
document.writeln("test");

出现这两个警报窗口。还有另一个问题。我尝试了一些变体来跟踪这个问题:

document.writeln(document.getElementById('test0').value);
document.writeln(document.getElementById('test2').value);    
window.alert("testing");
document.writeln("test");
document.writeln("test");
document.writeln("test");
document.writeln("test");

test0test2是我的两个文本框的ID。当test0test2的值分别为12和3时,不会显示任何警告窗口,这就是HTML页面上显示的内容:

12

但是当我把这两条顶线放在这样的底部时:

window.alert("testing");
document.writeln("test");
document.writeln("test");
document.writeln("test");
document.writeln("test");
document.writeln(document.getElementById('test0').value);
document.writeln(document.getElementById('test2').value); //Now on the bottom

使用上面的相同文本框值,会出现警告窗口,这是HTML页面上显示的内容

test test test test

我的预期输出应该是这样的:

test
test
test
test
12
3

现在我很好奇,为什么当我只改变线的位置时,输出是非常不同的?我使用Document.Writeln()时出现了问题吗?

3 个答案:

答案 0 :(得分:4)

一旦用

写入文档
document.writeline("test");

删除所有现有HTML,包括 <input>框。如果它们不存在,document.getelementById("test0");将返回null

使用Firebug很容易找到,只需在控制台中编写document.writeln("test"),您就会看到所有元素都消失了。

答案 1 :(得分:0)

js函数测试的第一行

document.writeln(document.getElementById('test2').value); 

写入输入字段test2 ie-12的值并清除所有其他html元素, 因此,当您尝试访问dom中不存在的元素的属性时,将引发Uncaught TypeError: Cannot read property 'value' of null

答案 2 :(得分:0)

document.writeln()浪费时间,因为它不会做程序员通常打算做的事情。只需使用write()来渲染
标签。