无法让 preventDefault 工作:item.preventDefault 不是函数

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

我尝试创建一个 js 脚本,它首先阻止默认设置,只有第二次放手 link 移动菜单,但我无法让 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();
  }
}

正如我在评论中提到的。

问题出在方法 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 可以避免与 itemevent 类型混淆,如果您在 the docs 中看到关于 preventDefault 您可以更好地理解差异