用数组中的字符串填充div

时间:2015-08-11 05:33:35

标签: jquery arrays text random

我想让divs随机填充存​​储在jquery数组中的文本。 我的HTML看起来像

<div class="row">
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
</div>

在我的jQuery中,我有一个看起来像

的数组
var fruits = ["Apple", "Pear", "Orange"]

每个细胞应该随机填充一个水果,但是我坚持正确地迭代并用类细胞挑选每个div的随机值。这段代码显然不起作用:

$.each(fruits), function(fruit) {
    var fruit = fruits[Math.floor(Math.random()*fruits.length)];
    $('.row .cell').text(fruit);
}

如何让随机猜测恰好发生5次并正确填充div?

4 个答案:

答案 0 :(得分:5)

试试这个

$('.cell').each(function(){
   $(this).text(fruits[Math.floor(Math.random()*fruits.length)])
})

答案 1 :(得分:3)

这应该这样做:

&#13;
&#13;
var fruits = ['Apple', 'Pear', 'Orange'];
$('.cell').each(function(index) {
  $(this).text(fruits[Math.floor(Math.random()*fruits.length)]);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="row">
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
</div>
&#13;
&#13;
&#13;

您需要迭代.cell元素而不是fruits数组。希望这会有所帮助。

答案 2 :(得分:0)

试试这个解决方案

function getRandomInt(min, max) {
  return Math.random() * (max - min) + min;
}

此函数将生成数组的最小和最大长度之间的值,以便您获得适当的值。

$('.cell').each(function(){
   $(this).text(fruits[getRandomInt(0, fruits.length)]);
});

答案 3 :(得分:0)

$('.row .cell').text(fruit)会更改每个".cell"的文字 这是一个快速修正:

var fruits = ["Apple", "Pear", "Orange"]; 

$.each(fruits, function(i, fruit) {
 var fruit = fruits[Math.floor(Math.random()*fruits.length)];
 $('.cell').eq(i).text(fruit);
});