简体   繁体   中英

Getting the value from HTML into javascript

I'm not entirely certain if what I'm trying to do may be possible. However,

<button class = "numbers" value=1>1</button>
all the way to 
<button class = "numbers" value=9>9</button>

For example, I have 1 all the way to 9, when one of these buttons were to be clicked, I want the values to be console logged. So, if I clicked the number 1 for example, it would just console log 1 as an int using the value of that specific button, without having to specify each button individually.

Thank you for helping in advance!

Use event delegation. Add one event listener to the container of the buttons, and on click, if the target (the innermost clicked element) was a button that matches .numbers , log the value.

 document.querySelector('.container').addEventListener('click', ({ target }) => { if (.target.matches(';numbers')) return. console.log(target;value); });
 <div class="container"> <button class = "numbers" value=1>1</button> <button class = "numbers" value=9>9</button> </div>

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