Home >Web Front-end >JS Tutorial >Example code sharing of how JS randomly generates a verification code
This article mainly introduces in detail the specific method of js to randomly generate a verification code, which has certain reference value. Interested friends can refer to it
The verification codes I have come across before are all pictures. Today I came across a demo that uses js to generate random verification codes. I will try it and share it with you.
Effect:
html code:
<p>验证码:</p> <p id="login" onclick="change()"> <a href="#" rel="external nofollow" ></a> </p>
Set a click click event for p, js code As follows:
function getCode(n) { var all = "azxcvbnmsdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP0123456789"; var b = ""; for (var i = 0; i < n; i++) { var index = Math.floor(Math.random() * 62); b += all.charAt(index); } return b; }; function change() { document.getElementById("login").innerHTML = getCode(4); } window.onload = change;
Define a variable and let its value be 26 letters and ten numbers from 0 to 9.
Math.random() causes the system to randomly select a pseudo-random double value greater than or equal to 0.0 and less than 1.0.
For example: Math.random()*62 The value obtained:
Math.floor is rounding down a number, before It has been mentioned in the blog. The
charAt method can return the character at the specified position, which has been mentioned in the blog before.
These are already very familiar, so just think of them as a review.
Get four random numbers and splice them into the p tag. You get the desired effect.
The above is the detailed content of Example code sharing of how JS randomly generates a verification code. For more information, please follow other related articles on the PHP Chinese website!