1. 程式人生 > >小程式驗證碼

小程式驗證碼

驗證碼:
<input bindinput="makecodeInput" type="text">

<view bindtap="getcode" class="makecode">{{code}}</view><button bindtap="login">登入</button>

index.js

data: {

code: "",

makecode:"",

},

//獲取輸入驗證碼

makecodeInput:function(e){

this.setData({

makecode:e.detail.value

})

},

// 登入

login: function() {

if(this.data.makecode != this.data.code){

wx.showToast({

title: '驗證碼不正確',

icon: 'none',

duration: 2000

})

}

},

//驗證碼

createCode() {

var code;

//首先預設code為空字串

code = '';

//設定長度,這裡看需求,我這裡設定了4

var codeLength = 4;

//設定隨機字元

var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

//迴圈codeLength 我設定的4就是迴圈4次

for (var i = 0; i < codeLength; i++) {

//設定隨機數範圍,這設定為0 ~ 10

var index = Math.floor(Math.random() * 10);

//字串拼接 將每次隨機的字元 進行拼接

code += random[index];

}

//將拼接好的字串賦值給展示的code

this.setData({

code: code

})

},

/*** 生命週期函式--監聽頁面載入*/

onLoad: function(options) {

this.createCode();

},

getcode: function() {

this.createCode();

},