Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
Cómo obtener el valor del botón con JS

¿Cómo puedo obtener el valor de un botón cuando hay muchos botones múltiples creados? Actualmente en mi archivo Javascript lo tengo, así que mi historial de búsqueda hace un botón en una lista con un "valor" de la ciudad que está etiquetada.

Cuando hago clic en el botón que se hizo, me sale indefinido.

 function recentSearch(city) { var addCity = document.createElement("button"); addCity.setAttribute("value", city); addCity.textContent = city; document.getElementById("searchHistory").append(addCity); cities.push(city); localStorage.setItem("searches",JSON.stringify(cities)); }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Si está agregando tantos botones, use la delegación de eventos . Agregue un oyente al contenedor principal, agregue sus botones y luego, en la función de oyente, verifique si el elemento en el que se hizo clic es un botón y registre su valor.

 const searchHistory = document.querySelector('#searchHistory'); // Add one listener to the container that calls `handleClick` searchHistory.addEventListener('click', handleClick, false); function handleClick(e) { // Destructure the nodeName and value from // the clicked element, and log the value if the // element is a button const { nodeName, value } = e.target; if (nodeName === 'BUTTON') { console.log(value); } } function recentSearch(city) { var addCity = document.createElement('button'); addCity.value = city; addCity.textContent = city; searchHistory.append(addCity); } const cities = ['London', 'Rome', 'New York', 'Seoul', 'Kingston']; for (const city of cities) { recentSearch(city); }
 <div id="searchHistory"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

El siguiente código registrará el valor del botón en la consola cuando se haga clic en él.

 function recentSearch(city) { var addCity = document.createElement("button"); addCity.setAttribute("value", city); addCity.textContent = city; addCity.onclick = (e)=>{ console.log(e.target.getAttribute('value')); //or whatever other code you want to do onclick } document.getElementById("searchHistory").append(addCity); cities.push(city); localStorage.setItem("searches",JSON.stringify(cities)); }
about 4 years ago · Juan Pablo Isaza Relatório

0

Intente usar atributos de datos . Hacen que su código sea más fácil de leer y proporcionan una excelente manera de pasar datos dentro de los elementos, y puede acceder a sus datos usando element.dataset.<attribute_name> , en este caso e.target.dataset.value (desde dentro de los botones haga clic en el oyente).

 cities = [] function recentSearch(city) { // FOR DEMO ONLY:: if (!city) city = "city " + Math.ceil(Math.random() * 1000); var addCity = document.createElement("button"); addCity.setAttribute("data-value", city); addCity.textContent = city; addCity.addEventListener('click', e => { console.log(`my city is: ${e.target.dataset.value}`); }) document.getElementById("searchHistory").append(addCity); cities.push(city); // localStorage.setItem("searches",JSON.stringify(cities)); }
 <div id='searchHistory'> </div> <button onclick='recentSearch()'>Make City</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda