Не могу заставить работать preventDefault: item.preventDefault не является функцией - PullRequest
2 голосов
/ 28 мая 2020

Я пытаюсь создать сценарий js, который сначала блокирует значение по умолчанию и только второй раз позволяет go ссылаться на мобильные меню, но я не могу заставить preventDefault работать, ошибка: item.preventDefault не является функцией . остальные в порядке, .setAttribute работает.

это мой сценарий, который я безуспешно пробовал:

var hasChild = document.querySelectorAll(".menu-item-has-children a");
hasChild.forEach(setPrevent);

function setPrevent(item) {
  item.setAttribute('data-active', 'false');
  item.addEventListener("click", respButAction);
  item.preventDefault();
  // this.preventDefault();
}

function respButAction(item) {
  isaActive = this.getAttribute('data-active');
  console.log(isaActive);

  if (isaActive == 'false') {
    this.setAttribute('data-active', 'true');
    // item.setAttribute('data-active', 'true');
    item.stopPropagation();
    // this.stopPropagation();
  }
  if (isaActive == 'true') {
    this.setAttribute('data-active', 'false');
    // item.setAttribute('data-active', 'false');
    item.preventDefault();
    //this.preventDefault();
  }
}

1 Ответ

1 голос
/ 28 мая 2020

, как я упоминал в комментарии.

Проблема в методе setPrevent(item), здесь вы не можете вызвать item.preventDefault();, потому что переменная item является фактическим элементом DOM.

Я бы предложил 2 изменения: 1. удалить вызов в методе setPrevent(item) 2. переименовать переменную в методе respButAction(item)

пример:

var hasChild = document.querySelectorAll(".menu-item-has-children a");
hasChild.forEach(setPrevent);

function setPrevent(item) {
    item.setAttribute('data-active', 'false');
    item.addEventListener("click", respButAction);
    // remove: item.preventDefault();
}

function respButAction(event) {
    isaActive = this.getAttribute('data-active');
    console.log(isaActive);

    if (isaActive == 'false') {
         this.setAttribute('data-active', 'true');
         event.stopPropagation();
    }
    if (isaActive == 'true') {
         this.setAttribute('data-active', 'false');
         event.preventDefault();
    }
}

С этим новое имя переменной event вы избегаете путаницы с типами item и event, если вы видите в документах примерно из preventDefault, вы можете лучше понять разницу

...