Home > Web Front-end > JS Tutorial > Example code sharing of how JS randomly generates a verification code

Example code sharing of how JS randomly generates a verification code

黄舟
Release: 2017-06-01 09:14:47
Original
2224 people have browsed it

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>
Copy after login

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;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template