简体   繁体   中英

How to get the value of a button inside click eventListener

I'm trying to show the value of a button when that button is clicked. If I write the code for this inside the eventListener the alert pops up but there is no text showing.

I have tried moving the alert above the eventListener and inside the for loop and this shows the correct values when the page loads.

HTML for buttons:

<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>

You need to to add a parameter argument eg e to the event listener or use arguments[0] .

Then you can use e.target.value to get the value of the button.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM