如何在div框内自动生成随机数?刷新页面后再次更改。
HTML code。
<div class="grid" data-row="0" data-column="0"></div>
<div class="grid" data-row="0" data-column="1"></div>
<div class="grid" data-row="0" data-column="2"></div>
<div class="grid" data-row="0" data-column="3"></div>
<div class="grid" data-row="0" data-column="4"></div>
......
<div class="grid" data-row="4" data-column="0"></div>
<div class="grid" data-row="4" data-column="1"></div>
<div class="grid" data-row="4" data-column="2"></div>
<div class="grid" data-row="4" data-column="3"></div>
<div class="grid" data-row="4" data-column="4"></div>
JS代码。
function random() {
var x = Math.floor((Math.random() * 25) + 1);
$(".grid").text(x);
}
答案 0 :(得分:1)
您必须使用JQuery的.each()
方法遍历所有div
元素并在该循环内生成随机数。继续生成随机数并继续申请div
。见下文
$('.grid').each(function () {
var x = Math.floor((Math.random() * 25) + 1);
$(this).text(x)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid" data-row="0" data-column="0"></div>
<div class="grid" data-row="0" data-column="1"></div>
<div class="grid" data-row="0" data-column="2"></div>
<div class="grid" data-row="0" data-column="3"></div>
<div class="grid" data-row="0" data-column="4"></div>
<div class="grid" data-row="4" data-column="0"></div>
<div class="grid" data-row="4" data-column="1"></div>
<div class="grid" data-row="4" data-column="2"></div>
<div class="grid" data-row="4" data-column="3"></div>
<div class="grid" data-row="4" data-column="4"></div>
答案 1 :(得分:1)
试试这个,这应该对你有所帮助,我对代码进行了一点评论,可能会有所帮助
// get all grid rows
var arr = document.querySelectorAll('.grid');
// loop over grid array
arr.forEach( function(el){
// generate random number
var x = Math.floor((Math.random() * 25) + 1);
// pass that number to element node
el.innerText = x ;
});
&#13;
<div class="grid" data-row="4" data-column="0"></div>
<div class="grid" data-row="4" data-column="1"></div>
<div class="grid" data-row="4" data-column="2"></div>
<div class="grid" data-row="4" data-column="3"></div>
<div class="grid" data-row="4" data-column="4"></div>
&#13;