[英]JavaScript - Why doesn't my code run when "Document.querySelector().value" is outside function + how do I get function to run on input number change?
I would like some help please.我需要一些帮助。
I managed to make my code work after finding a similar question on Stack Overflow, but the method I've been trying previously doesn't seem to work at all.在 Stack Overflow 上找到一个类似的问题后,我设法让我的代码工作,但我之前一直在尝试的方法似乎根本不起作用。
My code is very simple, if the number is 2 and I click the button, the message will say "Correct".我的代码很简单,如果数字是 2 并且我单击按钮,消息会说“正确”。 If the number is anything else, it will say "Wrong".
如果数字是别的,它会说“错误”。
Below is the HTML下面是 HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<input type="number">
<p>Message</p>
<button>Update</button>
</body>
</html>
Here is the JavaScript code that works Codepen link这是适用于Codepen 链接的 JavaScript 代码
const message = document.querySelector("p")
const button = document.querySelector("button")
function myFunction() {
const number = document.querySelector("input").value;
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
Here is the code that doesn't work Codepen link这是不起作用的代码Codepen 链接
const message = document.querySelector("p")
const button = document.querySelector("button")
const number = document.querySelector("input").value
function myFunction() {
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
My question is, why doesn't my second JavaScript code work?我的问题是,为什么我的第二个 JavaScript 代码不起作用? Is it possible to keep the number const outside of the function (keep the const variable global)?
是否可以将数字 const 保留在 function 之外(保持 const 变量全局)?
As the tutorials I'm watching suggest you keep variables outside functions to prevent DRY.正如我正在观看的教程建议您将变量保留在函数之外以防止 DRY。
Also, how can I get the code to run without having to click the "update" button each time?另外,我怎样才能让代码运行而不必每次都单击“更新”按钮?
eg if I type 2, the message will automatically say "Correct".例如,如果我输入 2,消息将自动显示“正确”。
Thank you very much in advance.非常感谢您提前。
const number needs to be in the function, otherwise the const will be null always const number 需要在 function 中,否则 const 将始终为 null
function myFunction() {
const number = document.querySelector("input").value
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
Live update on keyup inputfield keyup 输入字段的实时更新
const inputfield = document.querySelector("input");
inputfield.addEventListener("keyup", myFunction);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.