Add attribute to dynamically created object

1

I'm trying to add a data-id to objects that will be created dynamically, well the point is I want to do this as soon as the document or my object loads without the need to click etc, see the way I tried.

For example:

$(document).on('ready','.letras',function(){

    $(this).attr('data-id',faixas2[k]['id_faixa']);



    });

or

$(document).on('ready', function(){

$('.letras').attr('data-id',faixas2[k]['id_faixa']);



    });

It does not roll at all.

    
asked by anonymous 12.09.2016 / 16:40

2 answers

1

With jQuery, you can do it using each , see an example below, where after execution, all elements with the class letters receive an attribute called data-id with the value of the array valores :

$(document).ready(function (){
    $('.letras').each(function(indice_do_array){
        var valores = ["Teste1", "Teste2", "Teste3", "Teste4"];
        $(this).attr('data-id',valores[indice_do_array]);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><liclass="letras">Teste 1</li>
  <li class="letras">Teste 2</li>
  <li class="letras">Teste 3</li>
  <li class="letras">Teste 4</li>
</ul>
    
12.09.2016 / 16:54
1

By the code I believe that the amount of items in array tracks2 is equal to the number of classes and that you intend to assign those values in the divs with the .letras class, the .each method has the argument where you receive the index.

$(document).ready(function() {
  var faixas = ["faixaA", "faixaB", "faixaC"];

  $(".letras").each(function(index) {
    $(this).attr("data-id", faixas[index]);
  });
});
.letras {
  font-size: 75px;
  font-weight: bold;
  border-radius: 2px;
  border: 1px solid black;
  width: 75px;
  height: 75px;
  background: #6a737c;
  color: white;
  float: left;
  margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="letras">A</div>
<div class="letras">B</div>
<div class="letras">C</div>
    
12.09.2016 / 16:55