I'm trying to write a form that generates a non-repeating random set of numbers from range (0,9) in a group of tags. I have written my javascript but i'm still not getting something right.
(function($) {
$(window).load(function() {
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var ranNum = shuffle([0,1,2,3,4,5,6,7,8,9]);
$('.test').each(function(){
$(this).html(ranNum);
});
})
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="jumbotron">
<div class="form-group">
<div class="btn-group">
<a href="#" class="btn btn-default test" id="1st">1</a>
<a href="#" class="btn btn-default test" id="2nd">2</a>
<a href="#" class="btn btn-default test" id="3rd">3</a>
<a href="#" class="btn btn-default test" id="4th">4</a>
<a href="#" class="btn btn-default test" id="5th">5</a>
<a href="#" class="btn btn-clear">Back</a>
</div>
</div>
<div class="form-group">
<div class="btn-group">
<a href="#" class="btn btn-default" id="6th">1</a>
<a href="#" class="btn btn-default" id="7th">2</a>
<a href="#" class="btn btn-default" id="8th">3</a>
<a href="#" class="btn btn-default" id="9th">4</a>
<a href="#" class="btn btn-default" id="10th">5</a>
<a href="#" class="btn btn-clear">Clear</a>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1" class="text-success">
<h5 class="text-success">PayCom PIN</h5>
</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="PIN Number Here">
</div>
<div class="form-group">
<a href="#" class="btn btn-clear">Previous</a>
<a href="#" class="btn btn-success">Buy Airtime</a>
</div>
</div>
what i'm getting is the array re-scheduled after every browser refresh, but with the a href
buttons containing the entire array, not singular values across each button that are non-repeating.
Please, how do i resolve this?
答案 0 :(得分:1)
您必须添加index
$('.test').each(function (index, element) {
$(element).html(ranNum[index]);
});
ranNum
是您的数组,您必须循环每个 HTML元素和每个数组元素。
答案 1 :(得分:1)
更简洁的方法可能是让您的数字数组像“游泳池”一样。每次你采取&#39;一个数字,它将它从池中删除。要从池中删除号码,请使用array.splice()
。
var arrayOfAvailableNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function getNumberAtRandom() {
var pos = Math.floor(Math.random() * arrayOfAvailableNumbers.length);
var item = arrayOfAvailableNumbers.splice(pos, 1);
return item[0];
}
$('.item').each(function() {
$(this).html(getNumberAtRandom());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
&#13;