jQuery - Typical duplicate use situation of the same code. How to proceed?

7

Being here doing my sites in php/mysql/html/css and learning more and more about jQuery I got into the situation where I should use the same code for two ids distinct.

How do I need to use the same code in two different places to run the same script as in this case is to open and close a slideToggle on a top form? So I know jQuery gives dick when we duplicate an id on the same page because, by logic, id is identity, it's unique.

jQuery(function(){

    jQuery("#botaodeacao").click(function(e) {  
        jQuery("#oformulario").slideToggle(1500);
    });

    jQuery("#botaodeacao2").click(function(e) {
        jQuery("#oformulario").slideToggle(1500);   
    }); 
    e.preventDefault();             
});

Alright, we can do it for classes but if you need to do with ids ...

    
asked by anonymous 09.08.2014 / 20:05

3 answers

6

Separate selectors with comma:

jQuery(function(){

    jQuery("#botaodeacao, #botaodeacao2").click(function(e) {  
        jQuery("#oformulario").slideToggle(1500);
    });

});

In fact the jquery selector works exactly the same way as a CSS selector, and has some more unique features.

link

link

    
09.08.2014 / 20:12
6

For this purpose there is the concept of classes, which can be used in more than one element:

HTML:

<div class="minha-classe">Uma div</div>
<div class="minha-classe">Outra div</div>

Javascript:

// as classes são referenciadas com um "." (ponto)
// ao invés do "#" que são para os ids
$(".minha-classe").façaAlgo(...);

In the above code, the id method will be executed for all elements that have the façaAlgo class.

    
09.08.2014 / 23:37
2

I leave one more answer with an approach not mentioned in the other answers.

I think however that using classes (as Andrey suggested) to group elements is better solution and more flexible / expandable than indicating elements 1 to 1.

Following the idea of grouping elements, you can use pseudo-selectors as ^=nome , that is, they look for elements whose id (or class, name, etc) begin with that string. So in this case:

jQuery("[id^=botaodeacao]").click(function(e) {  
    jQuery("#oformulario").slideToggle(1500);
});

This selector will fetch all elements whose id starts with botaodeacao regardless of how many. Some examples would be: "botaodeacao", "botaodeacao2", "botaodeacao_45", etc.

    
10.08.2014 / 00:55