WordPress Oxygen Builder中JS响应式视频适配报错问题
解决WordPress Oxygen Builder中JS报错"$ is not a function"的问题
问题原因
WordPress默认会禁用jQuery的$别名,避免和其他JavaScript库产生冲突,必须使用全称jQuery来调用,这就是你遇到$ is undefined错误的核心原因。
解决方案
方案1:全局替换$为jQuery
直接将代码中所有的$替换成jQuery即可正常运行:
// Find all YouTube videos // Expand that selector for Vimeo and whatever else var $allVideos = jQuery("video[src^='//site-web.fr']"), // The element that is fluid width $fluidEl = jQuery("body"); // Figure out and save aspect ratio for each video $allVideos.each(function() { jQuery(this) .data('aspectRatio', this.height / this.width) // and remove the hard coded width/height .removeAttr('height') .removeAttr('width'); }); // When the window is resized jQuery(window).resize(function() { var newWidth = $fluidEl.width(); // Resize all videos according to their own aspect ratio $allVideos.each(function() { var $el = jQuery(this); $el .width(newWidth) .height(newWidth * $el.data('aspectRatio')); }); // Kick off one resize to fix all videos on page load }).resize();
方案2:用自执行函数映射$
通过自执行匿名函数将jQuery作为参数传入,在函数内部可以正常使用$:
(function($) { // Find all YouTube videos // Expand that selector for Vimeo and whatever else var $allVideos = $("video[src^='//site-web.fr']"), // The element that is fluid width $fluidEl = $("body"); // Figure out and save aspect ratio for each video $allVideos.each(function() { $(this) .data('aspectRatio', this.height / this.width) // and remove the hard coded width/height .removeAttr('height') .removeAttr('width'); }); // When the window is resized $(window).resize(function() { var newWidth = $fluidEl.width(); // Resize all videos according to their own aspect ratio $allVideos.each(function() { var $el = $(this); $el .width(newWidth) .height(newWidth * $el.data('aspectRatio')); }); // Kick off one resize to fix all videos on page load }).resize(); })(jQuery);
方案3:结合DOM就绪事件(适配动态加载视频)
如果你的视频是通过Oxygen动态数据加载的,需要确保代码在DOM完全加载后执行,用jQuery(document).ready包裹:
jQuery(document).ready(function($) { var $allVideos = $("video[src^='//site-web.fr']"), $fluidEl = $("body"); $allVideos.each(function() { $(this) .data('aspectRatio', this.height / this.width) .removeAttr('height') .removeAttr('width'); }); $(window).resize(function() { var newWidth = $fluidEl.width(); $allVideos.each(function() { var $el = $(this); $el .width(newWidth) .height(newWidth * $el.data('aspectRatio')); }); }).resize(); });
额外注意
在Oxygen Builder中添加脚本时,确保脚本设置为在页脚加载,避免脚本在jQuery加载前执行导致报错。
内容的提问来源于stack exchange,提问作者Giulian Mjenaut
相关产品推荐
相关产品推荐

