Jquery Age Gate отключен на один год - PullRequest
0 голосов
/ 24 января 2020

Когда наступил 2020 год, мои возрастные ворота перестали работать и, похоже, отключились на один год. Я чувствовал, что смена 2019 на 2020 год это исправит, но, похоже, это не сработает. Любая помощь здесь будет с благодарностью. Спасибо!

Я думаю, это может быть простым решением, но я немного растерялся.

(function ($) {
  $.ageCheck = function (options) {
    var months = ['Month','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var month;
    const settings = $.extend({
      minAge: 21,
      redirectTo: 'index2.html',
      redirectOnFail: '',
      title: '',
      copy: '',
      successMsg: {
        header: 'Success!',
        body: 'You are now being redirected...'
      },
      underAgeMsg: 'Sorry, you are not old enough to view this site...',
      errorMsg: {
        invalidMonth: 'Please select a month.',
        invalidDay: 'Please select a day.',
        invalidYear: 'Please select a year.',
        underAge: 'You must be 21 years of age or older to view this site.'
      }
    }, options);

    const _this = {
      month: '',
      day: '',
      year: '',
      age: '',
      errors: []
    }

    function setValues() {
        const day = $('.ac-container .day').val();
        _this.month = $('.ac-container .month').val();
        _this.day = day.replace(/^0+/, ''); // remove leading zero
        _this.year = $('.ac-container .year').val();
      }

    function validate() {
        _this.errors = [];

        console.log(_this.month);

        if (_this.month == 0) {
          _this.errors.push(settings.errorMsg.invalidMonth);
        }

        if (/^([0-9]|[12]\d|3[0-1])$/.test(_this.day) === false) {
          _this.errors.push(settings.errorMsg.invalidDay);
        }

        if (/^(19|20)\d{2}$/.test(_this.year) === false) {
          _this.errors.push(settings.errorMsg.invalidYear);
        }
        clearErrors();
        displayErrors();
        return _this.errors.length < 1;
      }

    function clearErrors() {
        $('.errors').html('');
    }

    function displayErrors() {
        console.log("show errors");
        let html = '<ul>';
        for (let i = 0; i < _this.errors.length; i++) {
          html += '<li>' + _this.errors[i] + '</li>';
        }
        html += '</ul>';
        setTimeout( function() {
          $('.ac-container .errors').html(html);
        }, 200);
        setTimeout( function() {
          $(".ac-container .errors").show();
        }, 200);

      }
    function reCenter(b) {
        b.css('top', '${Math.max(0, (($(window).height() - (b.outerHeight() + 150)) / 2))}px');
        b.css('left', '${Math.max(0, (($(window).width() - b.outerWidth()) / 2))}px');
      }

      function buildHtml() {
        const copy = settings.copy;

        let html = '';
        html += '<div class="ac-overlay"></div>';
        html += '<div class="ac-container" style="padding: 1% 4% 0 1% !important;">';
        //html += `<h2>${settings.title}</h2>`;


        html += '<div class="fields" style="margin-top:15px;">';
        //html += `<p>${copy.replace('[21]', `<strong>${settings.minAge}</strong>`)}`; +'</p>';
        html += '<div><img src="images/decoration-1.png" /></div>';
        html += '<div><img src="images/enter-bday-2.png" /></div>';

        html += '<div class="errors" style="margin: 0 auto; padding: 15px 0 !important;"></div>';

        html += '<div style-"margin: 0 auto;"><select class="month">';

        for (let i = 0; i < months.length; i++) {
          html += '<option value="' + i + '">' + months[i] + '</option>';
        }

        html += '</select>';
        html += '<select class="day">';
        html += '<option value="Day">Day</option>';

        for (let i = 1; i < 32; i++) {
          html += '<option value="' + i + '">' + i + '</option>';
        }

        html += '</select>';
        html += '<select class="year">';
        html += '<option value="Year">Year</option>';

Здесь я думаю, что проблема в следующем (следующая строка:)

        for (let i = 2019; i > 1918; i--) {
          html += '<option value="' + i + '">' + i + '</option>';
        }

        html += '</select></div>';
        //html += '<h2>Please select your city</h2>';
        //html += '<select class="city">';
        //html += `<option value="0">City</option>`;
        //html += `<option value="Indianapolis">Atlanta</option>`;
        //html += '</select>';

        html += '<div class="enter" style="margin-top:1%;"><button><img src="images/button-enter.png?1" /></button></div>';
        html += '<div style="padding-top:15px !important;"><img src="images/legal-4.png" /></div>';
        html += '</div></div>';

        $('body').append(html);

        $('.ac-overlay').animate({
          opacity: 0.8,
        }, 500, function () {
          reCenter($('.ac-container'));
          $('.ac-container').css({
            opacity: 1,
          });
        });

        $('.ac-container .day, .ac-container .year').focus(function () {
          $(this).removeAttr('placeholder');
        });
      }
      function setAge() {
        _this.age = '';
        const birthday = new Date(_this.year, _this.month, _this.day);
        const ageDifMs = Date.now() - birthday.getTime();
        const ageDate = new Date(ageDifMs); // miliseconds from epoch
        _this.age = Math.abs(ageDate.getUTCFullYear() - 1970);
      }
      function setSessionStorage(key, val) {
        try {
          sessionStorage.setItem(key, val);
          return true;
        } catch (e) {
          return false;
        }
      }
      function handleSuccess() {
        console.log("success");
        const successMsg = '';
        $('.ac-container').html(successMsg);
        setTimeout( function() {
          $('.ac-container').animate({
            top: '-350px',
          }, 100, function() {
            $('.ac-overlay').animate({
              opacity: '0',
            }, 100, function () {
              if (settings.redirectTo !== '') {
                window.location.replace(settings.redirectTo);
                $(".gated_content").show();
              } else {
                $('.ac-overlay, .ac-container').remove();
              }
            });
          });
        }, 100);
      }
      function handleUnderAge() {
        _this.errors.push(settings.errorMsg.underAge);
        clearErrors();
        displayErrors();
        return _this.errors.length < 1;
        // const underAgeMsg = '<h3>${settings.underAgeMsg}</h3>';
        // $('.ac-container').html(underAgeMsg);
        // if (settings.redirectOnFail !== '') {
        //   setTimeout(() => {
        //     window.location.replace(settings.redirectOnFail);
        //   }, 2000);
        // }
      }


    if (sessionStorage.getItem('ageVerified') === 'true') {
      $(".gated_content").attr("style","display:block;");
      console.log("SHOW STUFF");
      window.location.replace(settings.redirectTo);
      return false;
    }

    buildHtml();

    $('.ac-container button').on('click', function() {
      setValues();
      if (validate() === true) {
        setAge();

        if (_this.age >= settings.minAge) {
          if (!setSessionStorage('ageVerified', 'true')) {
            console.log('sessionStorage not supported by your browser');
          }
          handleSuccess();
          $(".gated_content").attr("style","");
        } else {
          handleUnderAge();
        }
      }
    });

    $(window).resize(function() {
      reCenter($('.ac-container'));
      setTimeout(function() {
       reCenter($('.ac-container'));
      }, 500);
    });
  };

}(jQuery));

1 Ответ

0 голосов
/ 24 января 2020

Я считаю, что ваша ошибка связана с тем, что мы все еще в январе. Помните, что в JavaScript месяцы начинаются с нуля (поэтому январь равен нулю, а не 1), что может заставить ваш сценарий думать, что мы все еще находимся в 2019 году. Прямо сейчас ваш массив месяцев имеет январь в качестве значения 1, а не 0 (у вас «Месяцы» равны нулю).

new Date().getMonth(); // will return 0 right now, in January

Так что при создании HTML на основе массива месяцев вам нужно либо удалить первые «Месяцы» string или используйте i-1 вместо i для каждого значения параметра.

html += '<option value="' + (i - 1) + '">' + months[i] + '</option>';

Еще одно примечание: вы можете сэкономить время в будущем, заменив 2019 в for (let i = 2019; i > 1918; i--) { с new Date().getUTCFullYear() или new Date().getFullYear(), поэтому вам не придется обновлять эту строку каждый год.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...