How to identify equal classes in numerical order with jQuery?

-1

On my page I have dozens of buttons that, when clicked, change the link ( href ) of a a element, with the attr method. To avoid putting a class on each button, since there are many, I would like jQuery to identify the buttons with class .mudar in numerical order.

How I tried:

$(document).ready(function(){
  $(".mudar")[0].click(function(){
    $("#download").attr("href", "https://file1.zip");
  });
  $(".mudar")[1].click(function(){
    $("#download").attr("href", "https://file2.zip");
  });
  $(".mudar")[2].click(function(){
    $("#download").attr("href", "https://file3.zip");
  });
});


<a href="" id="download">baixar</a>

<button class="mudar">zip 1</button>
<button class="mudar">zip 2</button>
<button class="mudar">zip 3</button>

It did not work because I do not understand how this works. Can you help me with this?

    
asked by anonymous 15.12.2018 / 21:05

1 answer

1

You can get the index through index() :

$(document).ready(function(){
  $(".mudar").click(function(){
    var indice = $(this).index();
    $("#download").attr("href", "https://file"+indice+".zip");
  });
});

In your specific case, you could also get the number that contains the string and change the link through it:

var indice = $(this).html().replace( /^\D+/g, '');

Editing

After commenting and chatting I created this solution:

First put the name of the files in the name of the buttons and a p with the name of the custom file that will be downloaded:

<button name="file1" class="mudar">zip 1 <p style="display: none">azul</p></button>
<button name="file2" class="mudar">zip 2 <p style="display: none">preto</p></button>
<button name="file3" class="mudar">zip 3 <p style="display: none">amarelo</p></button>

Then use this code:

$(document).ready(function(){
  $(".mudar").click(function(){
    var file = $(this).attr("name");
    var nameFile = $(this).find('p').html();
    var download = $("#download");
    download.attr("href", "https://"+file+".zip");
    download.attr("download", nameFile);
  });
});
    
15.12.2018 / 21:15