我是 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");
test0
和 test2
是我的两个文本框的 ID。当 test0
和 test2
的值分别为 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()
的使用有问题吗?
最佳答案
一旦您在文档中写入
document.writeline("test");
您删除所有现有的 HTML,包括<input>
盒子。如果它们不存在,document.getelementById("test0");
将返回null
。
使用Firebug很容易找到,只需写document.writeln("test")
在控制台中,您会看到所有元素都消失了。
关于JavaScript 和 Document.Writeln() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12912696/