简体   繁体   中英

Extract button Id or label when clicked

My template has a series of buttons in this format:

<button class="button button1" onclick="showAlert(xxx)">Button 1</button>
<button class="button button2" onclick="showAlert(xxx)">Button 2</button>
...
<button class="button buttonN" onclick="showAlert(xxx)">Button N</button>

A few lines after those, I want to display this text:

<h2>Button {{x}} was clicked</h2>

How do I go about implement the Javascript function showAlert ? I am not familiar with Javascript that much. And what can I put in the variable {{x}} to achieve this alert? Thanks.

I hope I have been helpful

 function showAlert(x) { var y = document.getElementById('resText'); y.innerText = 'Button ' + x + ' was clicked' }
 <button class="button button1" onclick="showAlert('B1')">Button 1</button> <button class="button button2" onclick="showAlert('B2')">Button 2</button> <button class="button buttonN" onclick="showAlert('BN')">Button N</button> <h2 id="resText"></h2>

Using ES6 (More up to date JavaScript) to solve this. Don't forget to check it in IE for compatibility. If it doesn't work then you can Google "forEach alternative IE 9" etc.

This way you can still output all buttons in another loop and just use the "increment" value for the id .

 let buttons = document.querySelectorAll('button'); let outputText = document.getElementById('btn-num'); buttons.forEach(button => { button.addEventListener('click', event => { outputText.innerText = `Button ${event.currentTarget.getAttribute('data-id')} was clicked`; }) })
 <button class="button button1" data-id="1">Button 1</button> <button class="button button2" data-id="2">Button 2</button> <button class="button button3" data-id="3">Button 3</button> <button class="button button4" data-id="4">Button 4</button> <h2 id="btn-num">Please click a button...</h2>

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