对于我的任务,我正在尝试创建一个计算器网站,并在实现该计算器的打开和关闭按钮的过程中。我正在尝试访问输入的值,但始终收到以下错误:
assignment_4.html:62未捕获的TypeError:无法读取的属性“ 0” 空值 在HTMLButtonElement.buttons。(匿名函数)上。onclick
<script>
let buttons=document.querySelectorAll(".col-6");
for(let i=0; i<buttons.length; i++){
buttons[i].onclick=function(){
console.log(buttons[i].innerHTML);
if(buttons[i].innerHTML=='ON / OFF'){
console.log(document.getElementById("#display").value);
if(document.getElementById("#display").value=='OFF'){
this.value="0";
}
}
else{
}
}
}
</script>
<body>
<div class="container">
<div class="row">
<h1 class="col-12 text-center mt-5">JS Calculator</h1>
</div> <!-- .row -->
<div class="row">
<div id="calculator" class="mt-4 col-12 col-md-6 ml-md-auto mr-md-auto col-lg-4">
<div class="row">
<input type="text" id="display" class="col-12 text-right form-control" value="OFF" disabled>
</div> <!-- .row -->
<div class="row">
<button class="col-6 btn btn-lg btn-outline-dark">ON / OFF</button>
<button class="col-6 btn btn-lg btn-outline-dark">AC</button>
</div> <!-- .row -->
<div class="row">
<button class="col-3 btn btn-lg btn-outline-dark">7</button>
<button class="col-3 btn btn-lg btn-outline-dark">8</button>
<button class="col-3 btn btn-lg btn-outline-dark">9</button>
<button class="col-3 btn btn-lg btn-outline-dark">/</button>
</div> <!-- .row -->
<div class="row">
<button class="col-3 btn btn-lg btn-outline-dark">4</button>
<button class="col-3 btn btn-lg btn-outline-dark">5</button>
<button class="col-3 btn btn-lg btn-outline-dark">6</button>
<button class="col-3 btn btn-lg btn-outline-dark">x</button>
</div> <!-- .row -->
<div class="row">
<button class="col-3 btn btn-lg btn-outline-dark">1</button>
<button class="col-3 btn btn-lg btn-outline-dark">2</button>
<button class="col-3 btn btn-lg btn-outline-dark">3</button>
<button class="col-3 btn btn-lg btn-outline-dark">-</button>
</div> <!-- .row -->
<div class="row">
<button class="col-3 btn btn-lg btn-outline-dark">0</button>
<button class="col-3 btn btn-lg btn-outline-dark">.</button>
<button class="col-3 btn btn-lg btn-outline-dark">=</button>
<button class="col-3 btn btn-lg btn-outline-dark">+</button>
</div> <!-- .row -->
</div> <!-- #calculator -->
</div> <!-- .row -->
</div> <!-- .container -->
答案 0 :(得分:1)
获取元素时不需要#,因为它已经期望有ID。将您的通话更改为:
document.getElementById("display")
答案 1 :(得分:0)
答案 2 :(得分:0)
您需要为“ this”事件onclick更改回调内部的button [i]的引用。原因是到事件发生时,button变量尚未定义,因此引发了错误。
buttons[i].onclick=function(){
console.log(this.innerHTML);
...