jQuery:点击时间间隔限制

网站上有一个报告页面,用户可以去生成报告,为了用户体验,可以在按钮上设置一个时间,即当有人单击“生成报告”按钮时,页面不会让他们再次按下(例如再按 5 分钟)。
以前都是用Cookie,现在可以直接HTML5的页面缓存技术

可以使用本地存储来设置时间戳,并使用 jQuery 轻松设置禁用属性。

禁用点击:

$('#myButton').on('click', function() {
    var $this = $(this);
    $this.prop('disabled', true);
    localStorage.myButtonEnableAt = new Date().getTime() + 30000;

    setTimeout(function(){
        $this.prop('disabled', false);
        localStorage.myButtonEnableAt = null;
    }, 30000);
});

页面加载时,检查状态:

var now = new Date().getTime();
if (localStorage.myButtonEnableAt > now ) {
    $('#myButton').prop('disabled', true);
    setTimeout(function(){
        $('#myButton').prop('disabled', false);
        localStorage.myButtonEnableAt = null;
    }, localStorage.myButtonEnableAt - now);
}
posted @ 2025-05-10 08:56  Dy大叔  阅读(23)  评论(0)    收藏  举报