You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress分类菜单点击外部不关闭,自定义脚本未加载求助

解决WordPress子主题custom.js未加载及菜单点击外部关闭问题

一、先搞定custom.js未加载的核心问题

你用get_template_directory_uri()指向的是父主题目录,但你的custom.js存在子主题里,路径不对导致文件找不到。直接修改子主题functions.php里的代码:

function enqueue_custom_script() {
    // 改用get_stylesheet_directory_uri()定位子主题目录
    wp_enqueue_script("custom-script", get_stylesheet_directory_uri() . "/js/custom.js", array("jquery"), null, true);
}
add_action("wp_enqueue_scripts", "enqueue_custom_script");

同时确认子主题目录结构:必须有js文件夹,且custom.js确实在这个文件夹里,文件权限设为常规的644(确保服务器能读取)。

二、修正custom.js的内容错误

你的custom.js里混了<script>标签和外部jQuery引用,这完全没必要——WordPress已经通过依赖参数array("jquery")加载了自带的jQuery,js文件里只需要写纯代码:

$(document).ready(function() {
    var $menuButton = $('.category-btn');
    var $menu = $('.category-dropdown');

    $menuButton.on('click', function(e) {
        e.stopPropagation(); // 阻止事件冒泡,避免点按钮时触发document的点击事件
        $menu.toggle();
    });

    $(document).on('click', function(event) {
        if (!$menuButton.is(event.target) && !$menu.is(event.target) && $menu.has(event.target).length === 0) {
            $menu.hide();
        }
    });
});

加个小优化:按钮点击事件里的e.stopPropagation()能避免菜单刚展开就被document的点击事件关掉。

三、验证效果

修改后刷新页面,打开浏览器开发者工具:

  • 去网络面板搜custom.js,确认文件已加载
  • 看控制台,确保无报错
  • 测试功能:点分类按钮展开菜单,再点页面其他区域,菜单应该自动关闭

内容的提问来源于stack exchange,提问作者Scott Colling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:52:07