[003]小程序系列 | js实现防止用户重复点击(方法一)

本文介绍了一种在前端使用JS控制按钮禁用状态的方法,以防止因网络延迟或用户快速点击导致的数据重复提交问题,通过设置按钮显示状态和利用微信小程序API实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接先上存在问题的图片
在这里插入图片描述
原本ID属于一个唯一性的东西,但是由于网络等问题由于短时间内多次点击,导致产生不必要的数据,影响后续操作,在前端我们可以使用js来控制重复点击。
原本的代码:

formSubmit: function(res) {
    if (this.data.name && this.data.id && this.data.msg) {
      db.collection('class').where({
        id: _this.data.id
      }).get({
        success(res) {
          if (res.data.length) {
            $Message({
              content: '该班级ID已存在',
              type: 'error'
            });
          } else {
            db.collection('class').add({
              data: {
                .......................
              },
              success: function() {
                .......................
              }
            })
          }
        }
      })
    } else {
      $Message({
        content: '所有选项必填',
        type: 'error'
      });

    }
  }
解决办法

加个disable来控制按钮是否显示

<i-button wx:if="{{display}}" type="ghost" bind:click="formSubmit" type="primary">创建</i-button>

修改后得js

    _this.setData({
      display: false
    })
    if (this.data.name && this.data.id && this.data.msg) {
      db.collection('class').where({
        id: _this.data.id
      }).get({
        success(res) {
          if (res.data.length) {
            _this.setData({
              display: true
            })
            $Message({
              content: '该班级ID已存在',
              type: 'error'
            });
          } else {
            db.collection('class').add({
              data: {
               .......................
              },
              success: function() {
                ......................
              }
            })
          }
        }
      })
    } else {
      $Message({
        content: '所有选项必填',
        type: 'error'
      });

    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值