jQuery llama a la misma función cuando se hace clic en dos botones diferentes

I have a button with class try and when its clicked there is a function that is being called, now I want to create a button called start that will do the same, and I don't want to copy paste whole code in that button click handler, is there a way to say lets say if try or start do the following in jquery?

preguntado el 02 de mayo de 12 a las 19:05

4 Respuestas

I assume that since you said a button called start que start is the id. That is why I am using a # en lugar de un . para hacer referencia a él.

$('.try, #start').click(function(e){

if start is the class, then use this. # indicates an id, while . indicates a class.

$('.try, .start').click(function(e){

contestado el 02 de mayo de 12 a las 19:05

Move the handler code to a named function and bind the named function.

function someFunction() {

$('.try').on('click', someFunction);
$('.start').on('click', someFunction);

O en una línea

$('.try, .start').on('click', someFunction);

contestado el 02 de mayo de 12 a las 19:05

2 individual calls instead of using the $('.try, #start') selector? Any reason for that? - holandés432

too much writing, @Dutchie432 had the simplest answer - Grigor

@Dutchie432 Even though, I updated my post to have it in one line. I personally prefer having it in 2 lines as it looks more clear. - Selvakumar Arumugam

@Grigor Its more of a preference than writing. Again, it may be just me. Btw, For your case La respuesta de Mark is my recommendation. - Selvakumar Arumugam

@Vega if you can write less and do more, I don't think there is a reason not to, the other method is cleaner too. - Grigor

$('.start, .try').click(function(){
//do your thing here

assumes two buttons with different classes:

<button class='try'>try</button>
<button class='start'>start</button>

MUCH easier if you use one class:

<button class='trystart'>try</button>
<button class='trystart'>start</button>

//do your thing here

contestado el 02 de mayo de 12 a las 19:05

solo haz:

$('#start, .try').on('click', function(){ // both of them

o bien:

$('#start').on('click', function(){
   $('.try').click();         // trigger .try action

Or just call your function inside the click:

function myClickFunction(){
   // your code ...


contestado el 02 de mayo de 12 a las 19:05

it is not a function, it is code executed when a button is clicked that I can't put in a function - Grigor

than use my second example! $('#start').on('click', function(){ $('.try').click(); // trigger .try action }); This will trigger the code inside the .fun element, just like you you actually clicked the .try ! fun. - Roko C. Bulján

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.