0

私のアプリケーションでは、jqueryui の datepicker を使用しています。入力要素ごとに一意の ID が必要です。それをするために、

私はこの機能を使用します(例):

   var x = 100;

    $("a").on("click", function(){
        console.log(Math.floor(Math.random() * x ));
    })

私の質問は、乱数が繰り返されないことをどのように保証するかです。だから、IDの重複を避けることができます。

前もって感謝します..

4

4 に答える 4

1
//Object capable of generating random ids through recursion triggered by filtering result

    var uniqueRandom = {
        randoms: [],
        getRandom: function(){
            var random = Math.floor(Math.random() * 10); //Make this your size, I used 10 for easy testing
            if(this.randoms.filter(function(elem){ return elem == random}).length > 0){
               return this.getRandom();
            }else{
               this.randoms.push(random);
               return random;
            }
        }
    }

//Usage
    for(var i = 0; i < 10; i++){
       console.log(uniqueRandom.getRandom());
    }

作業例 http://jsfiddle.net/q6SRs/1/

于 2013-06-04T09:24:50.100 に答える
1

乱数を使用せず、代わりにカウンターを使用してください。

var x = 100;

$("a").on("click", function(){
  x++;
  console.log("id" + x);
});
于 2013-06-04T09:07:27.150 に答える