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

WordPress中Uncaught TypeError: $ is not a function错误求助

解决WordPress中jQuery "$ is not a function" 错误

核心原因

WordPress默认以noConflict模式加载jQuery,全局$变量会被释放,无法直接用来指代jQuery对象,这是触发错误的根本原因。

有效修复方案

方案1:通过ready回调参数传递$

修改image-carousel.js代码,将jQuery传入ready回调并命名为$,回调内部即可正常使用$:

jQuery(document).ready(function ($) {
    const swiper = new Swiper('.swiper', {
        direction: 'horizontal',
        loop: false,
        allowTouchMove: true,
        slidesPerGroup: 1,
        
        // 响应式断点配置
        breakpoints: {
            1700: {
                slidesPerView: 5,
                spaceBetween: 20,
            },
            960: {
                slidesPerView: 3,
                spaceBetween: 13,
            },
            730: {
                slidesPerView: 2,
                spaceBetween: 13,
            },
            550: {
                slidesPerView: 2,
                spaceBetween: 13,
            },
            1: {
                slidesPerView: 1,
                spaceBetween: 13,
            }
        },

        // 导航箭头配置
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
            disabledClass: 'disabled_swiper_button'
        },
    });
});

方案2:全局绑定$为jQuery(快速生效但不推荐)

若想在全局直接使用$,可在脚本开头添加绑定代码:

var $ = jQuery;

$(document).ready(function () {
    // 原有Swiper配置代码保持不变
});

额外代码优化建议

你的scripts.php存在样式与脚本handle重复的问题,会导致资源加载冲突,需修改:

// 原错误代码(样式handle与脚本handle重复)
wp_register_style( 'hunterpanels-image-carousel-js', 'https://fonts.googleapis.com/icon?family=Material+Icons' );

// 修改为唯一handle
wp_register_style( 'hunterpanels-swiper-icons', 'https://fonts.googleapis.com/icon?family=Material+Icons' );

另外,需注册并引入Swiper官方资源,否则new Swiper会触发新错误,示例:

// 在hunter_scripts函数中添加
wp_register_script( 'swiper-js', 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js', array(), '11.0.5', true );
wp_register_style( 'swiper-css', 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css', array(), '11.0.5' );

// 执行入队
wp_enqueue_script( 'swiper-js' );
wp_enqueue_style( 'swiper-css' );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:50:24