How to attach events to dynamically created elements and pass parameters?

Asked

Viewed 1,977 times

7

I have a table that is generated via and a certain column generates a link. As it has been implemented, currently, it writes a code with intrusive. Something like below:

return "<a href=\"#\" id=\"detalhe-nota-" + record.data.id + "\" class=\'modal-detalhe-nota\' onclick=\"exibirModalDetalheNota(" + record.data.id + ")\">" + value + "</a>";

The generated comes out something like:

<a href="#" id="detalhe-nota-80549984" onclick="exibirModalDetalheNota(80549984)">23628</a>

I would like to link the event click to this link by its id attribute, but since id is dynamic I don’t know how to do it. An alternative solution with would be using the markup modal-detalhe-nota, as below:

$(document).on("a.modal-detalhe-nota", "click", function(e) { });

From what I understood by the elements to be created dynamically, they should have their events linked in this way and not in the form below:

$("a.modal-detalhe-nota").on("click", function(e) {});

I have two doubts:

  • How to link the event to the id attribute?
  • How to pass a parameter to the function? Because this id that is generated dynamically is parameter.
  • I’ve done something like that. I remember that at the time I used only onclick passing the value I needed to the method. + 1 good question.

  • @Marconi, I’m looking for a way to do with non-intrusive javascript.

3 answers

1

In jQuery it is possible to assign events to a newly created element, even if it has not yet been inserted into body.

What I usually do is create this element and at the same time already assign your event by jQuery. Then I can add it to HTML.

Example:

function criaLinkDinamico(callback, i) {

  var $link = $('<a/>', {
               'class' : 'minha-classe',
               'id' : 'meu-id-dinamico' + i
             });

 return $link.click(callback);

}

Then something like:

 var links = [];

 for (var i = 1; i < 10; i++) {

    var link = criaLinkDinamico(function ()
    { 
       console.log($(this).attr('id'));

    }, i));

    links.push(link);
 }

 $('html').append(links);

If you need to pass a parameter to an element, you can encapsulate the callback.

Small example:

function criarCallbackParametro(nome)
{
  return function (e) {

    e.preventDefault();

    $('body').append(nome);
  }
}


$(function()
{
    $('#el-1').click(criarCallbackParametro('Wallace'));
  
    $('#el-2').click(criarCallbackParametro('Miguel'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="el-1">add Wallace</button>
<button id="el-2">add Miguel</button>

 $('.meu_elemento').click(criarCallbackParametro('wallace'));

 $('.meu_elemento').click(criarCallbackParametro('miguel'));
  • 1

    Just a performance tip, do not use append, and other functions that enter values in the gift within a for, you will access the gift every time, it is better to store the value that will go to the gift concatenating and after the to give the append... http://stackoverflow.com/questions/5925888/using-jquery-to-append-Inside-a-loop-there-must-be-a-Better-way

  • And if your callback function needs parameter, as you would?

  • It’s just an example. I won’t teach you good practices with jQuery because I don’t have time right now

  • In the reply I have already posted the first example that shows using callback. Just read it right. I did not pass the function direct, but declared before the for.

  • Your solution served me partially, but the solution below was the one that solved my problem effectively.

1


Using your workaround is possible. These ID’s can be added with a type attribute data-* where * should be replaced by a.

Modify the Javascript that generates the link to:

return '<a href="#" data-detalhe-nota="' +
  record.data.id + '" class="modal-detalhe-nota">' +
  value + '</a>';

jQuery has the function .data() that accesses attribute values data-* directly, this way it will not be necessary to pass as parameter.

$(document).on("a.modal-detalhe-nota", "click", function(e) {
  var id = $(this).data('detalhe-nota'); // obter o ID
});
  • Your answer answered exactly what I needed. The only difference that I set the anchor via jQuery even.

1

Utilizing everything you already have just by performing the .on dynamic by id:

$('a[id^="detalhe-nota-"]').on('click', function(){
    var id = $(this).attr('id');
    var numberId = id.replace(/\D/i, '');
    callfunction(numberId);
});

Browser other questions tagged

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