Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
¿Cómo escribir una sola función sin usar explícitamente sus clases/Id en JS?

Tengo un html como el siguiente,

 <input class="btn btn-primary button1" type="button" value="0"> <input class="btn btn-primary button2" type="button" value="0"> <input class="btn btn-primary button3" type="button" value="0"> <input class="btn btn-primary button4" type="button" value="0">

Puede haber any number of buttons in the HTML .

Pero, aunque aumenta la cantidad de buttons en el HTML, no puedo escribir cada vez en el JS como se muestra a continuación,

 $(".button1").click(function() { buttonVal(this); }); $(".button2").click(function() { buttonVal(this); }); $(".button3").click(function() { buttonVal(this); }); ...... for button 4 and so on....
 //Single function function buttonVal(ele) { var v = +$(ele).attr('value'); $(ele).attr('value', v > 2 ? 0 : v + 1); }

Cada valor de los botones será 0 inicialmente.

Cuando se hace clic en cada botón, los valores aumentarán en 1 y cuando el valor llegue a 3 , vuelva a hacer clic en el botón después 3 . El valor debe convertirse en 0 .

La misma condición se aplica a todos los botones recién agregados.

Necesito una single function , que admita cualquier número de botones cuando se agregue, en lugar de agregar cada botón al evento de clic en el JS y no llamando a sus classes explícitamente.

¿Podría alguien por favor ayudar?

Muchas gracias.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Solo intenta así

 $(".btn").click(function() { buttonVal(this); }); function buttonVal(ele) { var v = +$(ele).attr('value'); $(ele).attr('value', v > 2 ? 0 : v + 1); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="btn btn-primary button1" type="button" value="0"> <input class="btn btn-primary button2" type="button" value="0"> <input class="btn btn-primary button3" type="button" value="0"> <input class="btn btn-primary button4" type="button" value="0">

about 4 years ago · Juan Pablo Isaza Denunciar

0

recorra los botones y agregue el detector de eventos para cada uno

 let btns = document.querySelectorAll(".btn") btns.forEach(x => { x.addEventLisetner("click", () => { buttonVal(x); }) })

esto es js puro, así que no hay necesidad de jquery aquí

about 4 years ago · Juan Pablo Isaza Denunciar

0

<input class="btn btn-primary button" type="button" value="0"> <input class="btn btn-primary button" type="button" value="0"> <input class="btn btn-primary button" type="button" value="0"> <input class="btn btn-primary button" type="button" value="0"> $(".button").click(function() { buttonVal(this); }); function buttonVal(ele) { var v = +$(ele).attr('value'); $(ele).attr('value', v > 2 ? 0 : v + 1); }

U funciona en buenas condiciones, pero sobrescribe el código.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda