【问题标题】:Assigning value to id only once只给 id 赋值一次
【发布时间】:2013-12-10 05:32:23
【问题描述】:

我有一个问题困扰了我一段时间。

我有 14 个 div,每个 div 必须在每次页面加载时分配一个随机 ID(介于 1 和 14 之间)。 这些 div 中的每一个都有“.image-box”类,我尝试分配的 ID 的格式是“box14”

我的 JS 代码可以分配随机 ID,但我无法获得分配两次相同的 ID。

JavaScript

var used_id = new Array();

    $( document ).ready(function() {
        assign_id();

        function assign_id()
        {
            $('.image-box').each(function (i, obj) {
                random_number();
                function random_number(){
                number = 2 + Math.floor(Math.random() * 14);
                var box_id = 'box' + number;

                if((box_id.indexOf(used_id) !== -1) === -1)
                    {
                        $(this).attr('id',box_id);
                        used_id.push(box_id);
                    }


                else
                    {
                    random_number();
                    }   
                }
            });

        }

    });

感谢您的帮助,

干杯

【问题讨论】:

  • 必须是随机的吗? assign_id() 可以分配递增值吗?
  • 为什么要以这种方式分配 ID

标签: javascript jquery random


【解决方案1】:

嗯,random...

在分配 ID 时,不要使用随机生成的数字(根据您的经验,它可能会随机重复值),而是使用增量更新的计数器。

function assign_id() {
    var counter = 0;
    $('.image-box').each(function (i, obj) {
       $(this).attr('id','image-box-' + counter++); }   
    });
}

【讨论】:

    【解决方案2】:

    我想这就是你想要的,DEMO

    $(document).ready(function() {
        assign_id();
    });
    function assign_id() {
        var numberOfDiv = $('.image-box').length;
        var listOfRandomNumber = myFunction(numberOfDiv);
        $('.image-box').each(function(i, obj) {
            $(this).attr("id",listOfRandomNumber[i]);
        });
    };
    
    //Getting List Of Number contains 1 to the number of Div which is 
    //14 in this case.
    function myFunction(numberOfDiv ) {
        for (var i = 1, ar = []; i < numberOfDiv +1 ; i++) {
            ar[i] = i;
        }
        ar.sort(function() {
            return Math.random() - 0.5;
        });
        return ar;
    };
    

    【讨论】:

      【解决方案3】:

      我建议有一个像你一样的全局数组用于 user_id 并将分配的 div id 推送到数组中。然后您可以在将随机 id 分配给 div 之前进行检查。如果它被分配使用不同的。

      希望这会有所帮助。

      干杯。

      【讨论】:

        【解决方案4】:

        首先你将如何使用我的实现:

        var takeOne = makeDiminishingChoice(14);
        

        在这种情况下,takeOne 是一个函数,您最多可以调用 14 次以获得 1 到 14 之间的唯一随机数。

        例如,这将按随机顺序输出 1 到 14 之间的数字:

        for (var i = 0; i < 14; i++) {
                console.log(takeOne());
        }
        

        这是makeDiminishingChoice本身的实现:

        var makeDiminishingChoice = function (howMany) {
        
                // Generate the available choice "space" that we can select a random value from.
                var pickFrom = [];
                for (var i = 0; i < howMany; i++) {
                        pickFrom.push(i);
                }
        
                // Return a function that, when called, will return a value from the search space,
                // until there are no more values left.
                return function() {
        
                        if (pickFrom.length === 0) {
                                throw "You have requested too many values. " + howMany + " values have already been used."
                        }
        
                        var randomIndex = Math.floor(Math.random() * pickFrom.length);
                        return pickFrom.splice(randomIndex, 1)[0];
                };
        };
        

        【讨论】:

          【解决方案5】:

          如果您只想分配唯一值,最好使用增量值(或类似 (new Date).getTime())。但是,如果由于某种原因,您必须随机选择值(仅从 1-14 中),然后使用类似这样的方法来选择唯一/随机值

          var arrayId = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
          
          function getRandomId(array) {
              var randomIndex = Math.floor(Math.random() * (array.length));
              var randomId = array.splice(randomIndex, 1);
              return randomId[0];
          }
          

          现在getRandomId(arrayId) 将从您的数组中返回一个随机选取的值,然后删除该值以使其不再重复。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-08-02
            • 1970-01-01
            • 2015-01-13
            • 1970-01-01
            • 2020-11-09
            • 2013-01-17
            • 2023-04-09
            相关资源
            最近更新 更多