javascript - 下拉 Javascript 错误 : object doesn't support property or method 'matches'

标签 javascript jquery methods drop-down-menu multiple-matches

我正在使用以下 JavaScript 下拉菜单,它在除新的 Windows Edge 之外的所有浏览器中都能完美运行。

它显示这个错误:

SCRIPT438: Object doesn't support property or method 'matches'

脚本:

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

脚本来自:http://www.w3schools.com/howto/howto_js_dropdown.asp我认为它会与所有平台兼容。现在我已经实现了它,但在 Edge 中遇到了问题。

最佳答案

您似乎在尝试检查点击事件是否由具有 dropbtn 类的对象触发。

如果你使用 jQuery,你可以这样做:

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!$(event.target).hasClass('dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

如果您不使用 jQuery,您可以获取类名,然后检查 dropbtn 是否是其中之一。

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  var classes = event.target.className.split(' ');
  var found = false; var i = 0;
  while (i < classes.length && !found) {
      if (classes[i]=='dropbtn') found = true;
      else ++i;
  }
  if (!found) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

关于javascript - 下拉 Javascript 错误 : object doesn't support property or method 'matches' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859054/

相关文章:

Java Jersey - 在同一个@path 上使用不同参数的相同方法?

javascript - 无法获取 jQuery 日期选择器

javascript - JavaScript中的函数表达式与声明有什么区别?

php - 将 PHP 变量传递给 jQuery 整数

java - 对象中的字符串不等于 ArrayList 中同一对象的字符串

调用 main 函数方法时发生 Java 引用错误

javascript - 如何使用 jQuery 和 Ajax 在下拉列表中插入默认项并禁用它

来自数组值的 Javascript 动态变量名称 (Appcelerator Titanium)

java - javascript 中的城市/地址搜索自动完成

javascript - 有没有更好的方法来检测 nextUntil 是否定期停止?