Add attribute to dynamically created object

Asked

Viewed 365 times

1

I’m trying to add a data-id for objects that will be created dynamically, well the point is that I want to do it right when the document or my object is loaded, 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']);



    });

doesn’t happen at all.

  • What would be the content of faixa2?

  • The best thing would be to do this at the moment the object is created. When you say "dynamically created" you can show the code that does that?

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 array value 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>
  <li class="letras">Teste 1</li>
  <li class="letras">Teste 2</li>
  <li class="letras">Teste 3</li>
  <li class="letras">Teste 4</li>
</ul>

1

By code I believe that the number of items in the endpoint array is equal to the number of classes and that you intend to assign these values in the endpoints with the class .letras, the method .each has the argument where you get 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>
<div class="letras">A</div>
<div class="letras">B</div>
<div class="letras">C</div>

Browser other questions tagged

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