简体   繁体   English

将随机数插入类中

[英]insert random numbers into a class

If I do this: 如果我这样做:

$('.classname').html(Math.floor(Math.random()*10)+1);

All of "classname" is filled with the same number. 所有“classname”都填充相同的数字。 Is it possible to fill every instance of "classname" with a different random number? 是否可以使用不同的随机数填充“classname”的每个实例?

The only possible way I can think of solving this is to go through each instance of "class name" and apply a random number one by one. 我能想到解决这个问题的唯一可行方法是遍历“类名”的每个实例并逐个应用随机数。

.html() html的()

$(".classname").html(function(idx, oldValue) {
    return (Math.floor(Math.random()*10)+1);
});

fiddle 小提琴

the html method has an "overload" that accepts a function. html方法有一个接受函数的“重载”。 The function should return the value to set the inner html to. 该函数应返回值以将内部html设置为。 In your case you can do: 在您的情况下,您可以这样做:

$(".classname").html(function() {
    return (Math.floor(Math.random()*10)+1);
});

the function is actually called with two arguments. 该函数实际上是用两个参数调用的。 The first is the index of the element in the selection and the second is the current value of the elements inner html 第一个是选择中元素的索引,第二个是元素内部html的当前值

You can use jQuery's .each() function to iterate over each element matching the selector you provide - 您可以使用jQuery的.each()函数迭代匹配您提供的选择器的每个元素 -

$.each('.classname',function(index,elem){
  var newRandomNumber = (Math.random()*10)+1;
  $(elem).html(Math.floor(newRandomNumber));
});

For every iteration of the each() function, you'll have the index of the element you are on and the element itself in the elem parameters. 对于each()函数的每次迭代,您将获得所在元素的index以及elem参数中的元素本身。


http://api.jquery.com/jQuery.each/ http://api.jquery.com/jQuery.each/

try this 尝试这个

$('.classname').each(function(index) {
    $(this).html(Math.floor(Math.random()*10)+1);
});

Yes. 是。 The easiest way to do so would be using the jQuery each function: 最简单的方法是使用jQuery的每个函数:

$('.classname').each(function() {
    $(this).html(Math.floor(Math.random()*10)+1);
});

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

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