微信小程序随机验证码的实现

小程序上经常会有一些注册 申请页面需要用到随机验证码。具体实现方法不多说 直接上代码

   <view class='yanzhengma'>
        <text class='left'>{{code}}</text>
        <text class='right' bindtap='huanyizhang'>换一张</text>
    </view>

.yanzhengma {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.yanzhengma .left {
    font-family: Arial;
    font-style: italic;
    font-weight: bold;
    border: 0;
    letter-spacing: 3px;
    font-size: 18px;
    background-color: #ccc;
    padding: 10rpx;
    margin-right: 20rpx;
    color: blue;
}

Page({

    data: {

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
    //刚进入页面随机先获取一个
        this.createCode()

    },
    huanyizhang(){
        this.createCode()
    },
    createCode() {
        var code;
        //首先默认code为空字符串
        code = '';
        //设置长度,这里看需求,我这里设置了4
        var codeLength = 4;
        //设置随机字符
        var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        //循环codeLength 我设置的4就是循环4次
        for (var i = 0; i < codeLength; i++) {
            //设置随机数范围,这设置为0 ~ 36
            var index = Math.floor(Math.random() * 36);
            //字符串拼接 将每次随机的字符 进行拼接
            code += random[index];
        }
        //将拼接好的字符串赋值给展示的code
        this.setData({
            code: code
        })
    },




})

猜你喜欢

转载自blog.csdn.net/qq_41629498/article/details/81740504