WordPress页面嵌入代码报Uncaught TypeError: $ is not a function如何解决
错误原因
- WordPress 内置的 jQuery 默认开启了
noConflict()兼容模式,全局作用域下不会默认绑定$作为 jQuery 的别名,避免和其他JS库的命名冲突。 - 你现有代码中
jQuery(window).load(function($) {})的写法存在参数错误:窗口 load 事件回调的第一个参数是事件对象,不是 jQuery 实例,你这里拿到的$本质是事件对象,自然无法作为函数调用。
修复代码
你可以直接替换成如下写法,通过IIFE在局部作用域绑定 $ 别名:
<script> (function($) { $(window).on('load', function() { if ($(".default-hero .hero-image img").length) { const imgHeight = $(".default-hero .hero-image img").css("height"); console.log(imgHeight); $(".default-hero .inside .row").css("min-height", imgHeight); } }); })(jQuery); </script>
如果你不需要等待页面所有资源(如无关图片、字体)加载完成,只需要DOM结构渲染完成就执行逻辑,可以用更简洁的DOM Ready写法,jQuery的ready回调默认会把jQuery实例作为第一个参数传入,直接用$即可:
<script> jQuery(document).ready(function($) { if ($(".default-hero .hero-image img").length) { const imgHeight = $(".default-hero .hero-image img").css("height"); console.log(imgHeight); $(".default-hero .inside .row").css("min-height", imgHeight); } }); </script>
内容的提问来源于stack exchange,提问作者CodeForGood
相关产品推荐
相关产品推荐

