我一直在研究 JavaScript 中的一些基本表单验证。目前,我有一个简单的 HTML 表单,它有三个输入字段——两个需要数字输入,一个需要字符串输入。但是,我正在努力实现这一点。
const displayMessage = function (message) {
document.querySelector(".message").textContent = message;
};
const displayOtherMessage = function (message) {
document.querySelector(".message1").textContent = message;
};
document.querySelector(".check").addEventListener("click", function () {
const height = Number(document.querySelector(".height").value);
const weight = Number(document.querySelector(".weight").value);
const name = String(document.querySelector(".name").value);
if (!height && !weight && !name) {
displayMessage("Please enter a height, a weight and a name.");
} else if (!height || !weight || !name) {
displayMessage("Please enter a height, a weight and a name.");
} else if (height && weight && name) {
if (
typeof weight !== "number" ||
typeof height !== "number" ||
typeof name !== "string"
) {
displayOtherMessage(
"Height must be a number, weight must be a number and name must be a string."
);
}
displayMessage("");
alert(
`Thank you, ${name}! You said you weigh ${weight} kilograms and are ${height} metres tall.`
);
}
});
这是我正在努力解决的问题:
if (
typeof weight !== "number" ||
typeof height !== "number" ||
typeof name !== "string"
) {
displayOtherMessage(
"Height must be a number, weight must be a number and name must be a string."
);
}
当我尝试在第二个输入字段中提交“John”时,会显示 displayMessage。如何使 displayOtherMessage 改为显示?
这里的 HTML: