What are the advantages of passing a function on the jQuery "html" function?

4

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

See:

$(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 functions css , prepend , append and etc ...

At last, I'd like to know what benefits I could get through this jQuery functionality.

    
asked by anonymous 26.11.2015 / 19:57

1 answer

6

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

In practice it's the same as

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

If $(el) is a set of elements, the argument index can be useful too, in that the function may be even more interesting. I would save 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 this callback function is a reference to the iterated / selected object.

    
26.11.2015 / 20:59