简体   繁体   中英

How can I set a global click listener to grab the value from many buttons?

I have an array of buttons, which each hold a different value. I need to add an event listener to listen for when it has been clicked. The value of the button clicked will be pushed into a different array.

I feel like I need forEach , but can't quite fit it in.

 function placeBet() { var betBtn_nodelist = document.querySelectorAll('.bet_amount > button'); var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist); for (var i = 0; i < betButtonsArr.length; i++) { betButtonsArr[i]; } }
 <div class="bet_amount"> <button class="five" value="5">5</button> <button class="ten" value="10">10</button> <button class="fifty" value="50">50</button> <button class="hundred" value="100">100</button> </div>

You have to attach a click event handler for every item from your array .

 result = []; function placeBet(){ var betBtn_nodelist = document.querySelectorAll('.bet_amount > button'); var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist); for (let i = 0; i < betButtonsArr.length; i++) { betButtonsArr[i].onclick = function(){ result.push(this.value); console.log(result); } } } placeBet();
 <div class="bet_amount"> <button class="five" value="5">5</button> <button class="ten" value="10">10</button> <button class="fifty" value="50">50</button> <button class="hundred" value="100">100</button> </div>

You can do it this way using jquery :

 var values = [] $(document).on('click', 'button', function() { values.push(this.value) console.log(values) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> <div class="bet_amount"> <button class="five" value="5">5</button> <button class="ten" value="10">10</button> <button class="fifty" value="50">50</button> <button class="hundred" value="100">100</button> </div>

how can I set a global click listener to grab the value?

Yes, you have to set a global click listener for all buttons in only one object – <div class="bet_amount"> . If you set one click listener for each button then it is bad for the browser perfomance.

With e.target.nodeName == 'BUTTON' you can recognize the click on buttons inside "bet_amount" class element.

 var result = []; function placeBet() { var betAmount = document.querySelector('.bet_amount'); betAmount.onclick = function(e) { if(e.target.nodeName == 'BUTTON') { result.push(+e.target.value); //"+" is converting to integer console.log(result.join(',')) } }; } placeBet();
 <div class="bet_amount"> <button class="five" value="5">5</button> <button class="ten" value="10">10</button> <button class="fifty" value="50">50</button> <button class="hundred" value="100">100</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