<div class="spacing">
<h5>Bill</h5>
<label for="bill"></label>
<input id="bill" type="number" name="bill" value="">
</div>
<script>
const bill = document.querySelector("#bill");
bill.addEventListener("input", function (e) {
console.log(bill.value);
})
</script>
我总是犯这个错误--未捕获的TypeError:无法读取null的属性"addEventListener"。
试试这个。在文档准备好之前,您正在读取控件。
解决方案1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
const bill = document.getElementById("bill");
bill.addEventListener("input", function (e) {
console.log(bill.value);
})
});
</script>
解决方案2没有JQuery
<script>
function printVal() {
const bill = document.getElementById("bill");
if (bill != null) {
bill.addEventListener("input", function (e) {
console.log(bill.value);
});
}
}
</script>
<div class="spacing">
<h5>Bill</h5>
<label for="bill"></label>
<input id="bill" type="number" name="bill" onkeypress="printVal();">
</div>
您必须将其转换为整数
<script>
const bill = document.querySelector("#bill");
bill.addEventListener("input", function (e) {
var a = parseInt(bill.value);
console.log(bill.value);
console.log(typeof a);
})
</script>
脚本标记应位于要应用处理程序的html之后,最好位于关闭body
标记之前。
另一种实现此功能的方法是使用事件委派。输入处理程序附加到文档。输入元素的检测是在处理程序函数中完成的。在这种情况下,脚本的位置并不重要。
示例
<script>
document.addEventListener(`input`, evt => {
if (evt.target.id === `bill` && evt.target.value.trim().length) {
console.log(evt.target.value);}
});
</script>
<div class="spacing">
<h5>Bill</h5>
<label for="bill"></label>
<input id="bill" type="number" name="bill" value="">
</div>
这个错误可能是Bravo先生在评论中提到的调试问题。我得到的输出与您给出的代码相同。
const bill = document.querySelector("#bill");
bill.addEventListener("input", function(e) {
console.log(this.value); // You can use `this` keyword
});
<div class="spacing">
<h5>Bill</h5>
<label for="bill"></label>
<input id="bill" type="number" name="bill" value="">
</div>
但下面的代码给了我错误,因为你得到了Uncaught TypeError: Cannot read property 'addEventListener' of null
<script>
const bill = document.querySelector("#bill");
bill.addEventListener("input", function(e) {
console.log(this.value);
});
</script>
<div class="spacing">
<h5>Bill</h5>
<label for="bill"></label>
<input id="bill" type="number" name="bill" value="">
</div>
将脚本移动到</body>
标记之前,以便在尝试访问DOM之前确保DOM已成功加载,或者在对其执行任何操作之前使用DOMContentLoaded
事件检查DOM是否已加载。
您还应该引用传递给侦听器的事件的目标值,而不是bill
。
window.addEventListener('DOMContentLoaded', () => {
const bill = document.querySelector("#bill");
bill.addEventListener('input', (e) => {
console.log(e.target.value);
});
});
<div class="spacing">
<h5>Bill</h5>
<label for="bill"></label>
<input id="bill" type="number" name="bill" value="">
</div>