【问题标题】:Fill divs with strings from array用数组中的字符串填充 div
【发布时间】:2015-11-03 05:08:38
【问题描述】:

我想让 div 随机填充存​​储在 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?

【问题讨论】:

    标签: jquery arrays text random


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 你也可以使用index of each()
    【解决方案2】:

    应该这样做:

    var fruits = ['Apple', 'Pear', 'Orange'];
    $('.cell').each(function(index) {
      $(this).text(fruits[Math.floor(Math.random()*fruits.length)]);
    });
    <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>

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

    【讨论】:

    • 哈! @DGS 打败了我 :)
    【解决方案3】:

    试试这个解决方案

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

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 1970-01-01
        • 2017-02-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多