我有以下 JavaScript。
<html>
<head>
<script language="JavaScript">
function fdivisible()
{
document.write("<h1> Just a javascript demo</h1>");
var x=document.forms["aaa"]["txt1"].value;
alert(x);
}
</script>
</head>
<body>
<form action="#" name="aaa">
Enter a no. : <input type="text" name="txt1" id="txt1" />
<input type="button" value="Click" onclick="fdivisible();">
</form>
</body>
</html>
问题是,JS 函数的第一行正在执行,其余的都被忽略了。如果我注释掉第一行,其余代码将被执行。谁能给我解释一下为什么会这样?
最佳答案
因为调用 document.write
隐式调用 document.open
,它会清除调用它的文档:
If a document exists in the target, this method clears it
调用 document.write
后,您尝试获取引用的元素不再存在于 DOM 中,并抛出错误。如果您查看错误控制台,它应该类似于以下内容:
TypeError: Cannot read property 'txt1' of undefined
关于javascript - 为什么 document.write() 之后的代码没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13820535/