我试图在单击按钮时显示其值。如果我在eventListener中为此编写代码,则会弹出警报,但不会显示任何文本。
我尝试将警报移动到eventListener上方和for循环内,这将在页面加载时显示正确的值。
按钮的HTML:
<button class="buttonA" value="A">A</button>
<button class="buttonB" value="B">B</button>
<button class="buttonC" value="C">C</button>
<button class="buttonD" value="D">D</button>
<button class="buttonE" value="E">E</button>
<button class="buttonF" value="F">F</button>
<button class="buttonG" value="G">G</button>
<button class="buttonH" value="H">H</button>
<button class="buttonI" value="I">I</button>
<button class="buttonJ" value="J">J</button>
Javascript:
<script>
var allButtons = document.querySelectorAll('button[class^=button]');
for (var i = 0; i < allButtons.length; i++) {
var value = allButtons[i].value;
alert(value); //this works and shows all values on page load
allButtons[i].addEventListener('click', function() {
try {
alert(value); //this shows a blank pop-up when a button is clicked
}
catch(error) {
console.log(error);
}
});
}
</script>
答案 0 :(得分:4)
您需要添加参数自变量,例如e
到事件监听器,或使用arguments[0]
。
然后,您可以使用e.target.value
来获取按钮的值。
document.querySelectorAll('button[class^=button]').forEach(button => {
button.addEventListener('click', onClickEvent);
});
function onClickEvent(e) {
try {
alert(e.target.value); // or `arguments[0].target.value`
} catch (error) {
console.log(error);
}
}
<button class="buttonA" value="A">A</button>
<button class="buttonB" value="B">B</button>
<button class="buttonC" value="C">C</button>
<button class="buttonD" value="D">D</button>
<button class="buttonE" value="E">E</button>
<button class="buttonF" value="F">F</button>
<button class="buttonG" value="G">G</button>
<button class="buttonH" value="H">H</button>
<button class="buttonI" value="I">I</button>
<button class="buttonJ" value="J">J</button>