本文主要是介绍微信小程序多个按钮点击互不影响禁用实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这段代码主要实现的是当有多个按钮时,需要改变按钮的内容,比如点击第一个按钮,按钮禁用并内容改为五秒后可点击,但此时不影响第二个按钮点击,每个按钮都是可以禁用5秒后再点击,就是互不影响
Page({data: {buttonStates: {}, // 用于存储按钮的状态},onButtonClick: function (e) {const btnId = e.currentTarget.dataset.btnId;if (!this.data.buttonStates[btnId]) {// 点击后设置按钮状态为禁用const buttonStates = this.data.buttonStates;buttonStates[btnId] = true;this.setData({buttonStates: buttonStates,});// 5秒后恢复按钮可点击状态setTimeout(() => {const buttonStates = this.data.buttonStates;buttonStates[btnId] = false;this.setData({buttonStates: buttonStates,});}, 5000);// 在这里可以添加按钮点击后的逻辑console.log(`按钮 ${btnId} 被点击了`);}},
});
<view class="button" data-btn-id="button1" bindtap="onButtonClick">按钮1</view>
<view class="button" data-btn-id="button2" bindtap="onButtonClick">按钮2</view>
<!-- 添加更多按钮... -->
以下是一个案例
<van-button disabled='{{(buttonStates[index]||buttonCounted[index])?true:false}}' bindtap="resetBox" data-btn-id="{{index}}" data-item="{{item}}"> {{ buttonCounted[index] > 0 ? '倒计时 ' + buttonCounted[index] + ' 秒' : '重启盒子' }}</van-button>
Page({/*** 页面的初始数据*/data: {buttonStates:{}, //点击禁用按钮的状态buttonCounted:{}, //倒计时的时间数据状态},resetBox(e) {const btnId = e.currentTarget.dataset.btnId;// btnId 传递过来的索引号if (!this.data.buttonStates[btnId]) { //当第一次点击即数据为空,取反即为true// 点击后设置按钮状态为禁用const buttonStates = this.data.buttonStates;const buttonCounted = this.data.buttonCounted;buttonStates[btnId] = true;buttonCounted[btnId] = 100;this.setData({buttonStates: buttonStates,buttonCounted:buttonCounted});// 每秒将按钮内的时间减1setInterval(()=>{const buttonCounted= this.data.buttonCountedbuttonCounted[btnId] = buttonCounted[btnId]-1;this.setData({buttonCounted: buttonCounted,});},1000)// 100秒后恢复按钮可点击状态setTimeout(() => {const buttonStates = this.data.buttonStates;buttonStates[btnId] = false;this.setData({buttonStates: buttonStates,});}, 100000);console.log(this.data.buttonStates);//下面可以写当按钮点击后的逻辑代码-------}
})
这篇关于微信小程序多个按钮点击互不影响禁用实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!