简体   繁体   English

我不明白jQuery .each()和.html()方法是如何工作的

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

Im Timo. 我是蒂莫。 I'm new at web programming and I have this issue. 我是网络编程的新手,我有这个问题。 I have made a simple html table with 3 rows. 我制作了一个包含3行的简单html表。 Each td has to have a random numeric value. 每个td必须具有随机数值。 My problem is that my code puts the same value at every td element. 我的问题是我的代码在每个td元素上放置相同的值。

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

Down below is my js code: 下面是我的js代码:

        $(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);

        });


    };

This is because you're generating a single random value then using that for each of the td s, rather than generating a new one for each td . 这是因为你生成一个随机值,然后使用每个td s,而不是为每个td生成一个新的td So: 所以:

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

In other words, generate the random value inside the loop, not outside of it. 换句话说,在循环内生成随机值,而不是在循环之外。

Furthermore, understand that, inside each callbacks, the context, ie this , points to the element being considered. 此外,要理解,在each回调中,上下文(即this )指向正在考虑的元素。 So you don't need 所以你不需要

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

but merely 但仅仅是

$(this).text(...

$.each() is essentially a foreach loop. $.each()本质上是一个foreach循环。 You need to create a new random value on each iteration. 您需要在每次迭代时创建一个新的随机值。

Like this: 像这样:

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);

  });
}

It's because your random value is generated before the each statement, so the same value is being used each time. 这是因为您的随机值是在每个语句之前生成的,因此每次都使用相同的值。

Move your Math.random()*100 into your .text() and all should work. 将Math.random()* 100移动到.text()中,一切都应该有效。

The problem has nothing to do with .each() or .html() . 该问题与.each().html()无关。 You have generated the random value just once and setting the same value to each of the td. 您只生成了一次随机值,并为每个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);

        });


    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM