简体   繁体   中英

Can`t get preventDefault to work: item.preventDefault is not a function

I try to create a js script That firstly block default and only second time let go to link for mobile menus, but I can not get preventDefault to work, the error is: item.preventDefault is not a function. the others are ok, the.setAttribute is working.

this is my script i tried with no luck:

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();
  }
}

as I mentioned in the comment.

The issue is in the method setPrevent(item) , here you can't call item.preventDefault(); because the item variable is the actual DOM element.

I would suggest 2 changes: 1. remove the call in the method setPrevent(item) 2. rename the variable in the method respButAction(item)

example:

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();
    }
}

With this new variable name event you avoid confusion with item an event types, if you see in the docs from about the preventDefault you can understand the difference better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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