简体   繁体   中英

auto generate random number inside div box?

how to auto-generate random number inside the div box? and change again after refreshing the page.

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 code .

function random() {
  var x = Math.floor((Math.random() * 25) + 1);
  $(".grid").text(x);
}

You have to use JQuery's .each() method to loop through all the div element and generate random number inside that loop. Keep generating the random number and keep applying to div . See below

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

Try this, this should help you,, I commented the code a little, might be of help

 // 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 ; }); 
 <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM