最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - insert random numbers into a class - Stack Overflow

programmeradmin1浏览0评论

If I do this:

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

All of "classname" is filled with the same number. Is it possible to fill every instance of "classname" with a different random number?

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.

If I do this:

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

All of "classname" is filled with the same number. Is it possible to fill every instance of "classname" with a different random number?

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.

Share Improve this question asked Jul 22, 2012 at 20:10 Jack S.Jack S. 2,8036 gold badges27 silver badges28 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

.html()

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

fiddle

the html method has an "overload" that accepts a function. The function should return the value to set the inner html to. 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

You can use jQuery's .each() function to iterate over each element matching the selector you provide -

$.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.


http://api.jquery./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:

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

评论列表(0)

  1. 暂无评论