我正在尝试更正表单,但javascript代码不会坚持。有谁知道问题可能是什么?我试过几个小时但浏览器不会识别任何javascript代码..
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page title</title>
<link rel="stylesheet" href="style/structure.css" type="text/css" />
<link rel="stylesheet" href="style/form.css" type="text/css" />
<link rel="stylesheet" href="style/theme.css" type="text/css" />
<script type ="text/javascript" src ="scripts/validate.js"></script>
</head>
文件结构有问题。我在文件夹“scripts”中有javascript文件,文件名是“validate.js”。一切都应该有效,但它不会......
的Javascript
window.onload = function() {
var form = document.getElementsByTagName("form")[0];
form.onsubmit = validate;
function validate() {
var firstName = document.getElementById("field_firstname").value;
if (firstName.length == 0) {
alert("Please enter your first name");
document.getElementById("field_firstname");
return false;
}
var lastName = document.getElementById("field_lastname").value;
if (lastName.length == 0) {
alert("Please enter your last name");
document.getElementById("field_lastname");
return false;
}
var email = document.getElementById("field_email").value;
if (email.length == 0) {
alert("Please enter your full e-mail adress");
document.getElementById("field_email");
return false;
}
if (confirm("Do you wish to complete the registration?")) {
return true;
} else {
alert("The registration was cancelled");
return false;
}
答案 0 :(得分:0)
您的代码正常运行(请参阅附带的代码段)。
我发现您发布的代码中存在一些支撑问题。验证和onload函数未关闭(缺失})
加载脚本时可能也会触发onload。您可能想测试是否调用onload函数。 (调试器; console.log()或警报('onload');
window.onload=function(){
var form = document.getElementsByTagName("form")[0];
form.onsubmit = validate;
}
function validate() {
var firstName = document.getElementById("field_firstname").value;
if (firstName.length == 0) {
alert("Please enter your first name");
document.getElementById("field_firstname");
return false;
}
var lastName = document.getElementById("field_lastname").value;
if (lastName.length == 0) {
alert("Please enter your last name");
document.getElementById("field_lastname");
return false;
}
var email = document.getElementById("field_email").value;
if (lastName.length == 0) {
alert("Please enter your full e-mail adress");
document.getElementById("field_email");
return false;
}
if (confirm("Do you wish to complete the registration?")) {
return true;
} else {
alert("The registration was cancelled");
return false;
}
}
<form>
field_firstname<input id="field_firstname" type="text"><br/>
field_lastname<input id="field_lastname" type="text"><br/>
field_email<input id="field_email" type="text"><br/>
<input type="submit">
</form>