I don't understand how jQuery.each () and .html () methods work

Im Timo. I am new to web programming and I have this problem. I created a simple html table with three rows. Each td must have a random numerical value. My problem is that my code puts the same value on every td element.

http://jsfiddle.net/timosergio/30ydu4oe/

Below is my js code:

        $(function() {

            randomValues();
            //alert(1);
        });


    var randomValues = function(){
        var $td = $('.table').find('td');

        // each td has to have a different random value

        var random_values = Math.random() * 100 ;

        $td.each(function(i){

            //console.log(i + ":" + Math.random() * 100);

            $td.eq(i).text(random_values);

        });


    };
+4
source share
4 answers

This is because you generate one random value and then use for each of tds, and not generate a new one for each td. So:

$td.each(function(i){
    $td.eq(i).text(Math.random(Math.random() * 100));
});

In other words, generate a random value inside the loop, not outside it.

, , each , .. this, .

$td.eq(i).text(...

$(this).text(...
+5

$.each() - , , foreach. .

:

var randomValues = function() {
  var $td = $('.table').find('td');

  // each td has to have a different random value
  $td.each(function(i){
    //console.log(i + ":" + Math.random() * 100);

    var random_value = Math.random() * 100 ;

    $td.eq(i).text(random_value);

  });
}
+1

This is because your random value is generated before each statement, so the same value is used every time.

Move your Math.random () * 100 to your .text () and everything should work.

0
source

The problem has nothing to do with .each()or .html(). You generated a random value only once and set the same value for each of td. You need to do this.

var randomValues = function(){
        var $td = $('.table').find('td');

        // each td has to have a different random value

       // var random_values = Math.random() * 100 ;

        $td.each(function(i){

            //console.log(i + ":" + Math.random() * 100);

            $td.eq(i).text(Math.random() * 100);

        });


    };
0
source

Source: https://habr.com/ru/post/1613091/


All Articles