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

Asked

Viewed 367 times

7

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

How to proceed when you need to use the same code in two different places to run the same script that in this case is to open and close a slideToggle in a top form? As far as I know jQuery takes it when we duplicate an id on the same page because by logic, id is identity, is unique.

jQuery(function(){

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

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

All right, we can do it by class, but if you need to do it with ids ...

3 answers

6

To this end there is the concept of classes, which differs from the ids, 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 method façaAlgo will be executed for all elements that have the class minha-classe.

6


  • 1

    Thank you @Jader. The people on this portal really are a special people. This is great information knowing that ps selectors work the same way because I’m great at CSS, it will be easier to learn.

2

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

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

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.