我想写一个简单的代码。该程序将提醒设备的类型";输入或输出";。这是代码:
<h1>Input or output device?</h1>
device name: <input type="text" id="device">
<br><br>
<script>
const x = document.getElementById("device").value;
</script>
<button onclick='alert(x === "mouse" ? "input device":"output device")'>Check now</button>
<script>
内部的代码在页面加载时只执行一次,因此,在页面存在期间,x
的值将是固定的。这就是为什么x
在键入任何内容时都不会更改的原因。
有很多解决方案。一种方法是将onChange
事件添加到输入中。
<input type="text" id="device" onChange="inputChanged()">
<script>
var x;
function inputChanged() {
x = document.getElementById("device").value;
}
</script>