javascript - 如何使用单独的 .js 文件正确地将 Fancybox 初始化为 WordPress?
问题描述
我进行了搜索,并在此处使用wp_add_inline_script
. 它有效。
但是,如果我想将我的初始化脚本保存到另一个 .js 文件中呢?这就是我一开始想要的。我怎样才能正确加载?我试过这个,但我的加载init-fancybox
必须太早,因为我得到一个错误。
(我的init-fancybox
脚本不是问题,因为它在使用正确加载时有效wp_add_inline_script
)
function fancybox_enqueues() {
wp_register_script( 'fancybox', get_theme_file_uri( '/assets/js/jquery.fancybox.min.js' ), array('jquery'), '3.5.7', true);
wp_register_script( 'init-fancybox', get_theme_file_uri( '/assets/js/init-fancybox.js' ), array('jquery','fancybox'), '1.0', true);
wp_register_style( 'fancybox-css', get_theme_file_uri( '/css/jquery.fancybox.min.css' ), '1.0');
if ( is_singular( 'item' ) ) {
wp_enqueue_script( 'jquery');
wp_enqueue_script( 'fancybox' );
wp_enqueue_script ('init-fancybox');
wp_enqueue_style( 'fancybox-css' );
}
}
add_action( 'wp_enqueue_scripts', 'fancybox_enqueues');
这是我得到的错误TypeError: $ is not a function
这是init-fancybox.js
$('[data-fancybox="single-item__gallery"]').fancybox({
buttons : [
"zoom",
"share",
//"slideShow",
"fullScreen",
//"download",
"thumbs",
"close"
],
thumbs : {
autoStart : false
}
});
解决方案
似乎在您的代码运行时没有加载 jQuery。尝试在它周围添加以下函数,以确保 jQuery 在您的代码运行之前存在:
jQuery(document).ready(function ($) {
// Your function goes here:
$('[data-fancybox="single-item__gallery"]').fancybox({
buttons: [
"zoom",
"share",
//"slideShow",
"fullScreen",
//"download",
"thumbs",
"close"
],
thumbs: {
autoStart: false
}
});
});
推荐阅读
- python-3.x - 在类中创建和检查可逆矩阵
- python - 如何在 python 中向多个组发送 smtplib 电子邮件?
- java - Jersey HTTP Delete,Put 响应状态:405(不允许的方法)
- python - 使用 Python 读取 CSV 并根据列条件随时间绘制 5 个系列
- python-3.x - Tableau Server 如何批量更新数据源服务器名称?
- html - IntelliJ 用标签替换文本
- c++ - c++ 数学库当域错误时会发生什么?
- flutter - 如何使用自定义字段登录 Google 帐户
- python - 类型错误:元类冲突
- javascript - Node.js 反向代理更改 URL 主机名而不是重定向到实际网站