Shopify迁移Dawn主题出现$不是函数错误该如何修复?
报错原因
$ is not a function 错误的核心诱因是Shopify的Dawn主题默认没有全局加载jQuery,你的代码执行时$对应的jQuery实例还未被定义,和你把函数定义放在第一行的操作没有关系。
修改思路评估
你之前把代码封装为函数的思路方向没有问题,但没有解决核心的jQuery依赖缺失问题,不需要完全重写原有代码,两种方案都可以实现正常运行:
方案一:改写为原生JS(更推荐,适配Dawn默认环境)
不需要额外引入jQuery,直接替换原有代码即可,没有依赖冲突风险,性能更好:
document.querySelector('.section__choose-texture').addEventListener('click', function(e) { // 事件委托匹配点击的.content元素 if (!e.target.closest('.content')) return const current = e.target.closest('.content') // 切换active状态 document.querySelectorAll('.content').forEach(el => el.classList.remove('active')) current.classList.add('active') // 赋值对应字段 document.querySelector('#prodTextureItem').value = current.dataset.texture document.querySelector('#productTexture').textContent = current.querySelector('h3').textContent const chooseCoffeeEl = document.querySelector('.section__choose-coffee') chooseCoffeeEl.style.display = 'block' // 计算滚动距离并平滑滚动 const headerHeight = document.querySelector('.site-header').offsetHeight const offsetTop = chooseCoffeeEl.offsetTop window.scrollTo({ top: offsetTop - headerHeight, behavior: 'smooth' }) })
方案二:保留原有jQuery写法
需要先补全jQuery依赖,再调整代码包裹方式避免加载顺序问题:
- 下载jQuery文件上传到主题的
assets目录 - 在主题的
theme.liquid文件的</head>标签前添加引入代码:{{ 'jquery.min.js' | asset_url | script_tag }} - 把原有代码用jQuery就绪语法包裹,解决变量指向问题:
jQuery(document).ready(function($) { // 原有代码直接放入即可,内部$会正常指向jQuery实例 $('.section__choose-texture').on('click', '.content', function ( ){ var current = $(this); $('.content').removeClass('active'); current.addClass('active'); $('#prodTextureItem').val(current.data('texture')); $('#productTexture').text(current.find('h3').text()); $('.section__choose-coffee').show(); var header_height = $('.site-header').height(), offset_top = $('.section__choose-coffee').offset().top, res = offset_top - header_height; $('html, body').animate({ scrollTop: res }, 'slow'); }); })
内容的提问来源于stack exchange,提问作者Adam Bell
相关产品推荐
相关产品推荐

