未捕获的类型错误:对象 #<HTMLLIElement> 没有方法“has”

Uncaught TypeError: Object #<HTMLLIElement> has no method 'has'

本文关键字:HTMLLIElement 有方法 has 错误 类型 对象      更新时间:2023-09-26

我正在尝试在我的一个菜单中使用 jQuery 的 has 方法来检查当前<li>中是否有任何<ul>。如果是,则显示它们,否则隐藏li.

但是使用has时,我收到此错误:

未捕获的类型错误:对象 # 没有方法"has"

我的代码:

$('nav ul li').click(function () {
    console.log(this.has('ul')); //Checking
    if ($(this).children('ul').is(":visible")) {
        $(this).children('ul').slideUp(250);
    } else {
        $(this).children('ul').slideDown(250);
    }
});

你稍后$(this)的原因是因为this不是jQuery对象。你仍然需要做$(this).has('ul').

请注意,您还可以使用 $(this).children('ul').slideToggle(250); 简化切换部分。