我网页的Javascript部分是't工作

Javascript portion of my webpage isn't working

本文关键字:工作 网页 Javascript      更新时间:2023-09-26

大家好,我正在用javascript编写一个非常简单的网页,遇到了一些我无法理解的东西。相比之下,我复制了w3schools中关于表单验证的代码,并试图将其与我的工作相集成。然而,我的不起作用,我真的不知道为什么。如果只是不运行,任何人的帮助都将不胜感激。

<!DOCTYPE html>
<html>
<head>
<title>Here is the javascript code </title>
<script type="text/javascript">
function validateform() {
 var x = document.body.forms["example"]["firstname_"].value;
 document.write("testing okay...made it into the function.");
 if( x == NULL || x == "") {
    document.write("testing okay it came into the if statement...Good.");
    alert("Sorry, you didn't enter in the correct information");
 }
    return false;
}
</script>
</head>
<body>
<form name="example" onsubmit="return validateform( )"  method="post" > 
 <input type="text" name="firstname_"> 
 <input type="submit" value="Enter Information">
</form>
</body>
</html>

这里有三件事:

  1. var x = document.body.forms["example"]["firstname_"].value;
  2. document.write
  3. NULL

表单属性在body上不存在使用:

 var x = document.forms["example"]["firstname_"].value;

在页面已加载时使用document.write将导致写入新文档,替换当前文档,从而破坏页面。

NULL也会抛出一个错误,因为它是未定义的。请使用小写的null

为什么您的代码没有执行;因为document.body.forms引发了一个错误,从而停止了进一步的脚本执行。

通过使用所有主流浏览器中的内置开发工具,您可以轻松地自行调试此类错误。您可以使用F12调出它们。