所以我对 javascript 很陌生,我想知道如何将我的 javascript 代码转换为 HTML 表单。我的想法是,我正在使用这个关于你的狗的年龄的网站,并制作一些更具互动性的东西,比如计算器。
我希望它看起来像这样:
我目前拥有的 HTML 是:
<form action="">
<h4>Size</h4>
<input type="radio" name="size" value="small" checked>Small<br>
<input type="radio" name="size" value="medium">Medium<br>
<input type="radio" name="size" value="large">Large<br>
<h4>Age</h4>
<p>Type in an age between 1 and 16.</p>
<input type="number" name="age" min="1" max="16"><br><br>
<input type="submit">
</form>
JavaScript 是这样的(它并不完美,但它可以工作),并且只打印到控制台。我希望它在用户按下提交按钮时打印给用户。
var dogSize = "medium"; // small, medium, or large?
var dogAge = 13; // type in an age between 1-16
// BASIC RULES
if (dogSize !== "small" && dogSize !== "medium" && dogSize !== "large") {
console.log("ERROR: Please type in either small, medium, or large");
}
else if (dogAge < 1 || dogAge > 16) {
console.log("ERROR: Type in an age between 1 and 16.");
}
// First 5 years
else if (dogAge === 1 && dogSize === "small") {
console.log("Your dog is 15 in human years.");
}
else if (dogAge === 1 && dogSize === "medium") {
console.log("Your dog is 15 in human years.");
}
else if (dogAge === 1 && dogSize === "large") {
console.log("Your dog is 15 in human years.");
}
etc...
我写了更多代码,但重要的是将 HTML 按钮与代码链接起来。
我真的很感激任何帮助! 谢谢。
您的问题非常广泛,因为您需要做的不仅仅是一件事。本质上,您需要为每个要连接到 JavaScript 的元素做 3 件事:
.getElementById()
,.querySelector()
,.querySelectorAll()
,
等)click
、change
、input
、submit
等)。.addEventListener()
完成的。在开始使用此解决方案之前,我强烈建议您研究使用 文档对象模型 (DOM) API、DOM 事件处理,特别是表单事件。
另一件事,如果您只想将其用作计算器而不是实际在任何地方提交数据,那么您不应该使用
submit
按钮,而应该只使用 button
按钮。
这是一个基本示例:
// Get a reference to the elements that we'll be working with:
let form = document.querySelector("form"); // Find the first <form> element in the document
let age = document.querySelector("input[name='age']"); // Find the first <input> with: name="age"
// Get all the <input> elements with name="size" and create an Array to store them in.
// .querySelectorAll() returns a list of the element nodes as a collection, but if
// we want to loop through that list using the .forEach() method for looping, we have
// to convert that list into a true JavaScript Array for the best compatibility across
// different browsers. Array.prototype.slice.call() takes the argument you pass to it
// and converts it into an Array.
let sizes = Array.prototype.slice.call(document.querySelectorAll("input[name='size']"));
// Set up event handlers for the elements.
// Here, we have three ways to trigger the calculation...
// 1. As the user enters a number for age
// 2. As the user changes the size
// 3. When the user clicks the button
// Of course, you could have each element hooked up to different
// functions if desired, but it doesn't seem like that is what you
// would want in this case.
age.addEventListener("input", calculate);
form.addEventListener("submit", calculate);
// We'll loop over all the radio buttons in the array
sizes.forEach(function(radioButton){
// and set each one up with an event handler
radioButton.addEventListener("click", calculate);
});
// These are the functions that were referenced above and that will be called
// when the events that they are tied to occur. Obviously, add you own custom
// code inside of each:
function calculate(){
console.log("...calculating...");
}
<form>
<h4>Size</h4>
<input type="radio" name="size" value="small" checked>Small<br>
<input type="radio" name="size" value="medium">Medium<br>
<input type="radio" name="size" value="large">Large<br>
<h4>Age</h4>
<p>Type in an age between 1 and 16.</p>
<input type="number" name="age" min="1" max="16"><br><br>
<input type="button" value="Calculate">
</form>
有多种方法可以实现这一目标。我认为这是完成该任务的简单方法。
您应该在触发提交事件后执行操作。你可以这样做:
form = document.getElementById("my-form");
form.addEventListener("submit", calculageAge, false);
您可能还想在将显示结果的表单内添加一个 HTML 元素。类似于
<span id="result"></span>
在你的calculateAge函数中,你应该修改DOM并用
显示结果// You should set this variable in your if...else statements
calculatedAge = "The age of the dog";
document.getElementById("result").innerHTML = calculatedAge;
向 html 文件上的元素添加特定的
id
。还可以使用右选择器来读取值
document.getElementById(INP_ID) : 获取 id 等于
INP_ID
的元素
document.getElementById(INP_ID).checked 检查id为INP_ID的元素是否被选中
document.getElementById(INP_ID).value; 获取元素的值。
var dogSize = "medium"; // small, medium, or large?
if (document.getElementById("r1").checked) {
dogSize = "small";
} else if (document.getElementById("r3").checked) {
dogSize = "large"
}
var dogAge = document.getElementById("age").value; // type in an age between 1-16
// BASIC RULES
if (dogSize !== "small" && dogSize !== "medium" && dogSize !== "large") {
console.log("ERROR: Please type in either small, medium, or large");
} else if (dogAge < 1 || dogAge > 16) {
console.log("ERROR: Type in an age between 1 and 16.");
} else if (dogAge === 1 && dogSize === "small") {
// First 5 years
console.log("Your dog is 15 in human years.");
} else if (dogAge === 1 && dogSize === "medium") {
console.log("Your dog is 15 in human years.");
} else if (dogAge === 1 && dogSize === "large") {
console.log("Your dog is 15 in human years.");
}
<form action="">
<h4>Size</h4>
<input type="radio" id="r1" name="size" value="small" checked>Small<br>
<input type="radio" id="r2" name="size" value="medium">Medium<br>
<input type="radio" id="r3" name="size" value="large">Large<br>
<h4>Age</h4>
<p>Type in an age between 1 and 16.</p>
<input id="age" type="number" name="age" min="1" max="16"><br><br>
<input type="submit">
</form>
更新
您可以使用它们来选择元素,而无需添加任何
id
或更改您的html代码
var radios = document.getElementsByName("size")
console.log(radios)
if (radios[0].checked) {
dogSize = "small";
} else if (radios[2].checked) {
dogSize = "large";
}
var dogAge = document.getElementsByName("age")[0].value; // type in an age between 1-16
用 JavaScript 计算狗的人类年龄的单行解决方案
如果您想使用 JavaScript 以人类年数计算您的狗的年龄,您可以使用以下公式并使用
prompt
和 alert
显示结果。通常使用的公式是:
公式
这是实现此目的的代码:
alert("Your dog's human age is: " + ((Number(prompt("What is the age of your dog?")) - 2) * 4 + 21));
说明:
prompt("What is the age of your dog?")
**:这要求用户输入狗的年龄。它返回一个字符串,因此我们需要将其转换为数字。
Number(prompt(...))
:将输入的字符串转换为数字。
公式计算:
alert(...)
:这会将结果显示为警报,显示狗的人类等效年龄。
替代版本(更具可读性): 为了更清晰起见,这是同一解决方案的稍微详细的版本:
let dogAge = Number(prompt("What is the age of your dog?"));
alert("Your dog's human age is: " + ((dogAge - 2) * 4 + 21));
此版本将狗的年龄存储在变量中(
dogAge
),使代码更易于修改和维护。
这应该可以帮助任何寻找简单解决方案来使用 JavaScript 计算狗的人类年龄的人。