What are the advantages of passing a Function in jQuery’s "html" function?

Asked

Viewed 69 times

4

I discovered by accident these days ago that in jQuery it is possible to pass a callback function to the function html.

Behold:

$(function ()
{
  $('body').html(function ()
  {
    return [1, 2, 3, 4, 5];
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

And not only that, but also for the functions css, prepend, append and etc...

Enfin, I would like to know what are the benefits I could draw through this jQuery feature.

  • 1

    $() selector + propriedade - That doesn’t explain itself ?

  • Sometimes I ask questions I already know the answer so I can help to have more content on the site @Edilson

1 answer

6


The idea of having a function as an argument is to be able to access the content before changing it. Like a getter inside the Setter.

In practice it is the same as

var valor = $(el).html();
var novoValor = valor + ' algo novo que mude o valor';
$(el).html(novoValor);

In the case of $(el) be a set of elements, the argument index can be useful too, in which the function can be even more interesting. It would save you having to do something like:

$(elementos).each(function(){
    var valor = $(this).html();
    var novoValor = valor + ' algo novo que mude o valor do elemento';
    $(this).html(novoValor);
});

can be done directly with:

$(elementos).html(function(index, conteudo){
    var novoValor = conteudo + ' algo novo que mude o valor do elemento';
    return novoValor ; // para evitar fazer: $(this).html(novoValor);
});

The this within that function callback is a reference to the iterated/selected object.

Browser other questions tagged

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