Estoy tratando de hacer que este programa agregue un carácter especial cuando se presiona el botón asignado para el carácter. El problema es que voy a tener muchas funciones. ¿Puedo de alguna manera hacer una función que pueda usar para todos los botones?
//These are buttons var aa = document.querySelector('#aa') var oo = document.querySelector('#oo') var uu = document.querySelector('#uu') var khii = document.querySelector('#khii') //This is the text box var textBox = document.querySelector('#typeIn') //Functions to add a character into the text box function addAa() { textBox.innerHTML += "ā"; } function addOo() { textBox.innerHTML += "ō"; } function addUu() { textBox.innerHTML += "ū"; } function addKhii() { textBox.innerHTML += "χ"; } //Telling the buttons to call on the functions when clicked aa.onclick = addAa oo.onclick = addOo uu.onclick = addUu khii.onclick = addKhiiAdemás: ¿por qué esto no funciona?
var aa = document.querySelector('#aa') var textBox = document.querySelector('#text') function addLetter(a) { textBox.innerHTML += a } aa.onclick = addLetter("ā")Esto solo agrega el carácter una vez en el cuadro de texto. Al hacer clic en el botón, no hace nada. ¿Porque hace eso?
Sí, puedes hacerlo con una sola función. Pasa el carácter como parámetro a la función. Como eso:
versión con addEventListener (preferido)
const btns = document.querySelectorAll('button'); const textBox = document.querySelector('#typeIn'); btns.forEach(b => { b.addEventListener('click', e => { textBox.innerHTML += e.target.getAttribute('data-char') }) }); #typeIn { margin:10px; padding: 10px; color: white; min-height:40px; background: gray; } <button data-char="aa">aa</button> <button data-char="X">X</button> <button data-char="ō">ō</button> <button data-char="ū">ū</button> <div id="typeIn"></div>En general, intente evitar los eventos onclick y use eventListener en su lugar.
Versión onclick Evento
const textBox = document.querySelector('#typeIn'); function add(what) { textBox.innerHTML += what; } #typeIn { margin:10px; padding: 10px; color: white; min-height:40px; background: gray; } <button onclick="add('aa')">aa</button> <button onclick="add('X')">X</button> <button onclick="add('ō')">ō</button> <button onclick="add('ū')">ū</button> <div id="typeIn"></div>Podrías hacer algo como esto:
<button data-value="A">A</button> <button data-value="B">B</button> <button data-value="C">C</button> document .querySelectorAll('button') // Use appropriate class name here .forEach(button => button .addEventListener("click", (e) => console.log(e.target.dataset.value) // Do whatever you want here ) )Aquí hay un enlace a un JsFiddle que he creado para demostración.