简体   繁体   English

即使在页面重新加载后点击一段时间后禁用按钮

[英]Disabling button after click for a certain period of time even after page reload

I am working on simple POS restaurant ordering system.我正在开发简单的 POS 餐厅点餐系统。 Here users can add items into their cart and easily checkout.在这里,用户可以将商品添加到他们的购物车中并轻松结帐。 I am trying to implement that user can only click once on checkout button for a specific time and when time's over button enable again.我正在尝试实现该用户只能在特定时间单击结帐按钮一次,并且当时间结束按钮再次启用时。

By now, I have disabled the button for specific time, but that is not good solution, because when page refresh, buttons are enabled again.到目前为止,我已经禁用了特定时间的按钮,但这不是一个好的解决方案,因为当页面刷新时,按钮会再次启用。

DEMO: Can be find here .演示:可以在这里找到。

Html: Html:

<body>
    <div>
        <button>checkout</button>
    </div>
</body>

Jquery: Jquery:

$.fn.disableFor = function(mins, secs) {
    var i = [],
    play = [];

    this.click(function() {
        var selector = $(this),
        inDex = $(selector).index(),
        prevText = $(selector).text();
        i[inDex] = 0;
        var inSeconds = mins * 60 + secs;

        $(selector).prop("disabled", "disabled");
        
        play[inDex] = setInterval(function() {
            if(inSeconds > 60){
                inSeconds = inSeconds - 1;
                var minutes = Math.floor(inSeconds / 60);
                var seconds = inSeconds % 60;
                if(minutes >= 1){
                    if(seconds.toString().length > 1){
                        $(selector).text(minutes + ":" + seconds + " minutes left");
                    }else{
                        $(selector).text(minutes + ":" + "0" + seconds + " minutes left");
                    }
                }else{
                    $(selector).text(seconds + " seconds left");
                }
            }else{
                if(inSeconds > 1){
                    inSeconds = inSeconds - 1;
                    if(inSeconds.toString().length > 1){
                        $(selector).text(inSeconds + " seconds left");
                    }else{
                        $(selector).text("0" + inSeconds + " seconds left");
                    }
                }else{
                    $(selector).prop("disabled", "");
                    clearInterval(play[inDex]);
                    $(selector).text(prevText);
                }                              
            }
        }, 1000);
    });
};

$(function() {
    $("button").disableFor(2,0); // First parameter stands for minutes and the second for the seconds.
});

You need to use browser localStorage to store the seconds.您需要使用浏览器localStorage来存储秒数。

Once you click on checkout button we will setItem time as the the seconds - In setIterval we will keep updated the time remaining in the button and once the time reaches the limit of end we will remove using removeItem the localStorage from the browser .单击结帐按钮后,我们将设置项目时间为seconds - 在setItem setIterval ,我们将不断更新按钮中剩余的时间,一旦时间达到结束的限制,我们将使用removeItembrowser中删除localStorage

If the user refreshes the checkout page (This is where your question comes in) - We click on the checkout button the we will check if there is any time remaining in the localStorage for our key we have set in before.如果用户刷新结帐页面(这是您的问题所在) - 我们单击结帐按钮,我们将检查localStorage中是否还有我们之前设置的密钥的剩余时间。

If there is no remaining time we will use start the clock at 1 minutes and 15 seconds OR else we will start at the time remaining using getItem in the localStorage .如果没有剩余时间,我们将使用1 minutes and 15 seconds开始时钟,否则我们将使用localStorage中的getItem从剩余时间start

I have tested this code and it works perfectly.我已经测试了这段代码,它运行良好。

Demo: (You need to try this in your own browser - localStorage is not supported in this snippet.)演示:(您需要在自己的浏览器中尝试此操作 - 此代码段不支持localStorage 。)

 $.fn.disableFor = function(mins, secs) { var i = [], play = []; this.click(function() { var selector = $(this), inDex = $(selector).index(), prevText = $(selector).text(); i[inDex] = 0; //Store seconds var inSeconds = mins * 60 + secs; //Get the previous stored seconds - check local storage var retrievedObject = localStorage.getItem('time'); if (retrievedObject) { inSeconds = retrievedObject } //Disable button $(selector).prop("disabled", "disabled"); play[inDex] = setInterval(function() { if (inSeconds > 60) { localStorage.setItem('time', inSeconds); //Set time again inSeconds = inSeconds - 1; var minutes = Math.floor(inSeconds / 60); var seconds = inSeconds % 60; if (minutes >= 1) { if (seconds.toString().length > 1) { $(selector).text(minutes + ":" + seconds + " minutes left"); } else { $(selector).text(minutes + ":" + "0" + seconds + " minutes left"); } } else { $(selector).text(seconds + " seconds left"); } } else { localStorage.setItem('time', inSeconds); //Set time again if (inSeconds > 1) { inSeconds = inSeconds - 1; if (inSeconds.toString().length > 1) { $(selector).text(inSeconds + " seconds left"); } else { $(selector).text("0" + inSeconds + " seconds left"); } } else { localStorage.removeItem('time'); $(selector).prop("disabled", ""); clearInterval(play[inDex]); $(selector).text(prevText); } } }, 1000); }); }; $(function() { $("button").disableFor(1, 15); // First parameter stands for minutes and the second for the seconds. });
 div { margin: 0 auto; padding: 10px; vertical-align: middle; background-image: -moz-linear-gradient(bottom, white 0%, #CCC 100%); background-image: -o-linear-gradient(bottom, white 0%, #CCC 100%); background-image: -webkit-linear-gradient(bottom, white 0%, #CCC 100%); background-image: -ms-linear-gradient(bottom, white 0%, #CCC 100%); background-image: linear-gradient(bottom, white 0%, #CCC 100%); } button { color: #2b2b2b; text-shadow: 0 1px 0 #999; font-size: 18px; font-weight: bold; text-transform: uppercase; cursor: pointer; margin: 0 5px; border-radius: 12px; -moz-box-shadow: 4px 4px 4px #CCC; -o-box-shadow: 4px 4px 4px #CCC; -ms-box-shadow: 4px 4px 4px #CCC; -webkit-box-shadow: 4px 4px 4px #CCC; box-shadow: 4px 4px 4px #CCC; } button:hover { color: #3c3c3c; background-image: -moz-linear-gradient(top, #CCC 0%, white 20%, #666 100%); background-image: -o-linear-gradient(top, #CCC 0%, white 20%, #666 100%); background-image: -ms-linear-gradient(top, #CCC 0%, white 20%, #666 100%); background-image: -webkit-linear-gradient(top, #CCC 0%, white 20%, #666 100%); background-image: linear-gradient(top, #CCC 0%, white 20%, #666 100%); } button:disabled { color: #999; cursor: default; background: #CCC; }
 <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div> <button>checkout</button> </div> </body>

I think this code is quite self-explanatory.我认为这段代码是不言自明的。 Let me know if something is not clear.如果有不清楚的地方,请告诉我。

I used localStorage (just like AlwaysHelping in his answer) which unfortunately doesn't work in StackOverflow's sandbox.我使用了 localStorage(就像他的回答中的 AlwaysHelping 一样),不幸的是它在 StackOverflow 的沙箱中不起作用。 You can save this as an html file and open it locally to test it.您可以将其另存为 html 文件并在本地打开以进行测试。

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <div> <button>checkout</button> </div> </body> <script> const button = $('button'); const pauseTime = 8 * 1000; // 8 seconds let cache = retrieveDisableTime(); let disabledTime; let currentTime; let interval; button.on('click', function(){ disabledTime = + new Date(); cache = {time: disabledTime}; saveDisableTime(cache); button.prop("disabled", "disabled"); setTimer(); }); if(shouldButtonBeOff()) { button.prop("disabled", "disabled"); setTimer(); } function shouldButtonBeOff() { disabledTime = cache? cache.time: false; currentTime = + new Date(); return disabledTime && disabledTime + pauseTime > currentTime; } function setTimer() { interval = setInterval(function() { console.log('Not yet ready'); if(.shouldButtonBeOff()) { console;log('READY'). button,prop("disabled"; false); clearInterval(interval), } }; 1000). } function saveDisableTime(obj) { localStorage,setItem('disableButton'. JSON;stringify(obj)). } function retrieveDisableTime() { return JSON.parse(localStorage;getItem('disableButton')); } </script>

Try this:尝试这个:

//start cookies functions
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
function removeCookie(cname) {
  document.cookie = cname+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
//end cookies functions

var cookieCheckout = getCookie('checkouttime');
var secondsTimeout = 0;
var delayTime = 2*60;
if (cookieCheckout && cookieCheckout != "") {// if we have cookie then set cookie seconds, when load page
  secondsTimeout = delayTime - Math.round((Date.now() - parseInt(cookieCheckout)) / 1000);
  if (secondsTimeout > delayTime) {
    removeCookie('checkouttime');
    //make checkout button enable
  } else {
    //make checkout button disable
  }
}

setCookie('checkouttime', Date.now(), 30);// set timestamp, when you click on enable checkout


if (secondsTimeout > delayTime) { //if time more then need limit then refresh timer, inside interval
  removeCookie('checkouttime');
  //make checkout button enable
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM