- 已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。
这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
昨天关门了。
Improve this question
为了将firstname
的值成功地从index.html
形式传输到index.js
逻辑中,必须更改以下代码中的哪些特定语法?
错误消息:
当前,index.js
的const firstnameInput = document.querySelector("input[firstname='firstname']");
行将firstname
的值读取为null
。
浏览器的"开发人员工具"选项卡中出现的错误是:
caught TypeError: Cannot set properties of null (setting 'isValid')
at index.js:4:24
错误消息引用的index.js
中的行是:
firstnameInput.isValid = () => !!firstnameInput.value;
但是从下面的代码中可以看到,firstnameInput
的值首先应该由const firstnameInput = document.querySelector("input[firstname='firstname']");
行引入。
索引代码. html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Validation</title>
<link rel="stylesheet" href="style.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div class="contact-banner">
<h1>Form Name</h1>
</div>
<form name="contact-form">
<div class="form-control">
<label>First Name</label>
<input name="firstname"
placeholder="First Name"
id="firstname-input" />
<div class="error hide">First Name is required</div>
</div>
<hr />
<button type="submit" id="submit">SUBMIT FORM</button>
<div id="success" class="success">Successfully submitted.</div>
<div id="fail" class="fail">Submission error.</div>
</form>
<script src="index.js"></script>
<script src="contact.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</body>
</html>
- 索引的代码. js:**
const form = document.querySelector("form[name='contact-form']");
const firstnameInput = document.querySelector("input[firstname='firstname']");
firstnameInput.isValid = () => !!firstnameInput.value;
const inputFields = [firstnameInput];
let shouldValidate = false;
let isFormValid = false;
const validateInputs = () => {
if (!shouldValidate) return;
isFormValid = true;
inputFields.forEach((input) => {
input.classList.remove("invalid");
input.nextElementSibling.classList.add("hide");
if (!input.isValid()) {
input.classList.add("invalid");
isFormValid = false;
input.nextElementSibling.classList.remove("hide");
}
});
};
form.addEventListener("submit", (e) => {
e.preventDefault();
shouldValidate = true;
validateInputs();
if (isFormValid) {
// TODO: DO AJAX REQUEST
}
});
inputFields.forEach((input) => input.addEventListener("input", validateInputs));
1条答案
按热度按时间bf1o4zei1#
应该是
代替