小程序中按鈕驗證碼倒計時


wxml文件:

<view>
  <button type="primary" bindtap="countdown" disabled="{{isDisabled}}">{{title}}</button>
</view>
<view>
  <button type="primary" bindtap="countdown1" disabled="{{isDisabled}}">{{title}}</button>
</view>

js文件

  data: {
    title:"發送驗證碼", // 按鈕中顯示的字符
    titleConst:"發送驗證碼", // 重置后的按鈕中顯示的字符
    count:3,   // 倒計時的秒數
    countConst:3, // 重置后的倒計時的秒數
    isDisabled:false // 按鈕是否禁用
  },  

  // setInterval中用箭頭函數,保證this和外部一致
  countdown: function(){
    let count = this.data.count;
    // 當count不為0開始倒計時,當count為0就關閉倒計時
    // 設置定時器
    var countdown = setInterval(() => {
      if( count == 0 ){
        this.setData({
          title:this.data.titleConst,
          count: this.data.countConst,
          isDisabled:false
        });
        // 取消定時器
        clearInterval(countdown);
      } else {
        this.setData({
          title:count-- + "s后重試",
          isDisabled:true
        });
      }
    }, 1000);
  },
  // 用that保存this,防止在setInterval中this被替換
  countdown1: function(){
    let that = this;
    let count = this.data.count;
    // 當count不為0開始倒計時,當count為0就關閉倒計時
    // 設置定時器
    var countdown = setInterval(function(){
      if( count == 0 ){
        that.setData({
          title:that.data.titleConst,
          count: that.data.countConst,
          isDisabled:false
        });
        // 取消定時器
        clearInterval(countdown);
      } else {
        that.setData({
          title:count-- + "s后重試",
          isDisabled:true
        });
      }
    }, 1000);
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM