首页 > 解决方案 > 如何使用单独的 .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
    }
  });

标签: javascriptphpjquerywordpressfancybox

解决方案


似乎在您的代码运行时没有加载 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
    }
  });

});


推荐阅读