JavaScript表单信息获取问题:document.forms方法返回undefined
为什么document.forms会返回undefined?
我仔细看了你的代码,问题主要出在这几个地方,导致你用document.forms时拿不到预期的对象:
document.write直接覆盖了整个页面
当你执行document.write(5+6)的时候,这个方法会清空当前页面所有的DOM内容——包括你写的表单。这时候后续再去访问document.forms,页面已经被重写了,自然找不到原来的表单元素,返回undefined。表单按钮默认是submit类型,会触发页面刷新
你表单里的<button>没有指定type="button",浏览器默认会把它识别为type="submit"按钮。点击它的时候,除了执行getFormValue函数,还会触发表单提交,导致页面刷新。页面刷新后,之前的DOM状态被重置,同样会出现找不到表单的情况。HTML标签未正确闭合
你的<button>标签没有闭合(应该写成<button onclick="getFormValue()">获取表单值</button>),浏览器解析DOM时可能出现结构异常,间接影响document.forms对表单的识别。
下面是修复后的完整代码:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function cos(sth){ var par = document.getElementById("para1"); par.style.color = 'blue'; par.style.fontSize="30px"; par.style.fontFamily="Impact,Charcoal,sans-serif"; } function getFormValue(){ // 替换document.write,用console.log输出避免覆盖页面 console.log(5+6); // 获取表单邮箱值 var emailVal = document.forms["myForm"]["email"].value; // 获取name字段(补充对应input元素) var nameVal = document.forms[0].elements["name"].value; console.log('邮箱:', emailVal); console.log('姓名:', nameVal); } </script> </head> <body> <p id ="para1">JavaScript Exercises - w3resource</p> <div> <button onclick="cos();">Style</button> </div> <form name="myForm"> <input type="text" name="name" placeholder="输入姓名"/> <input type="text" name="email" placeholder="输入邮箱"/> <!-- 指定button类型为button,避免提交表单 --> <button type="button" onclick="getFormValue()">获取表单值</button> </form> </body> </html>
修复说明:
- 把
document.write换成console.log,避免覆盖页面DOM; - 给表单按钮加上
type="button",阻止默认的表单提交行为; - 闭合了
<button>标签,还补充了一个name="name"的输入框(匹配你代码里访问的元素); - 分别输出邮箱和姓名的值到控制台,方便查看结果。
这样修改后,你点击"获取表单值"按钮,就能正常通过document.forms获取表单元素了,不会再出现undefined的情况。
内容的提问来源于stack exchange,提问作者aggre1234
相关产品推荐
相关产品推荐

