Модальная ошибка из-за неопределенной переменной, которая уже была объявлена - PullRequest
0 голосов
/ 22 сентября 2019

Я прохожу код, чтобы открывать и закрывать модалы.Все было хорошо до конца.Модал должен закрыться:

  • нажатием на кнопку «Закрыть»
  • нажатием на клавишу «ESC»
  • нажатие вне модального окна.

Первые два прошли нормально, но последний не работал.Когда я заглянул в консоль, у меня появилось сообщение, что "Uncaught ReferenceError: $modalContainer is not defined".

$modalContainer, однако, было объявлено в первых строках функции.Он работал через весь код и даже вне функции, в которой он был объявлен.

Я нашел два обходных пути, чтобы заставить его работать, но они не совсем лучшие практики: повторное объявление одной и той же переменной ИЛИ с использованиемdocument.querySelector('#modal-container') чтобы закончить работу.

// creates function to exhibit modal
function showModal() {
  var $modalContainer = document.querySelector('#modal-container'); //selects container
    $modalContainer.classList.add('is-visible'); // add visibility class
    }
// function to hide modal
function hideModal() {
  var $modalContainer = document.querySelector('#modal-container'); //selects container
  $modalContainer.classList.remove('is-visible'); //remove visibility class
}

// create event listener to show modal
document.querySelector('#modal-button').addEventListener('click', () => {
  showModal('This is not a headline', 'Here is a detail');
});

    //-- show modal --
function showModal(title, text) {
  var $modalContainer = document.querySelector('#modal-container');
  $modalContainer.innerHTML = '';
  // creates div for modal itself
  var modal = document.createElement('div');
  modal.classList.add('modal');

  // creates button to close modal and activate hideModal()
  var closeButtonElement = document.createElement('button');
  closeButtonElement.classList.add('modal-close');
  closeButtonElement.innerText = 'Close';
  closeButtonElement.innerHTML = "Close"; // new line
  closeButtonElement.addEventListener('click', hideModal); // new line

  // create H1 headline on Modal and message title variable
  var titleElement = document.createElement('h1');
  titleElement.innerText = title;

  // create <p> text on Modal and message text variable
  var contentElement = document.createElement('p');
  contentElement.innerText = text;

  //appends elements closebutton, titleand content to modal
  modal.appendChild(closeButtonElement);
  modal.appendChild(titleElement);
  modal.appendChild(contentElement);
  $modalContainer.appendChild(modal);

  // adds visibility class (?)
  $modalContainer.classList.add('is-visible');
};

// creates ESC shortcut to close modal
window.addEventListener('keydown', (e) => {
  var $modalContainer = document.querySelector('#modal-container');
  if (e.key === 'Escape' && $modalContainer.classList.contains('is-visible')) {
    hideModal();
  }
});

/* 
uncomment variable declaration and the modal closes as expected: with the "ESC" key, clicking on "Close" modal button and clicking outside the modal element.
*/

// var $modalContainer = document.querySelector('#modal-container');

// creates "Close" action by clicking outside modal
$modalContainer.addEventListener('click', (e) => {
  var target = e.target;
  if (target === $modalContainer) {
    hideModal();
  }
});

Я, вероятно, упускаю что-то простое здесь, но не могу найти ответ.Может ли кто-нибудь просветить меня, чтобы я мог понять, в чем проблема?Чтобы предоставить дополнительную информацию, кроме кода JavaScript, я создал Codepen со всеми HTML, CSS и JS: https://codepen.io/gobbet/pen/yLBGpzy

Заранее спасибо

Ответы [ 2 ]

0 голосов
/ 22 сентября 2019

Объявите $modalContainer глобально или, если это невозможно (perhabs создается при открытии модального режима), вы можете сделать следующее:

document.querySelector('body').addEventListener('click', (e) => { 
  if (e.currentTarget.id == 'modal-container') { 
    hideModal(); 
  } 
});
0 голосов
/ 22 сентября 2019

Каждый раз, когда вы объявляете $ modalContainer, он находится внутри функции, поэтому его область действия ограничена родительской функцией.В своем действии «Закрыть» вы добавляете прослушиватель событий в $ modalContainer, как если бы он был объявлен глобально, но он не существует глобально.

...