jQuery 没有加载到 WordPress 中的自定义 js 文件
jQuery not loading into custom js file in WordPress
我在位于 /mytheme/js/live-search.js 的自定义 js 文件中编写了一些代码 在 js 文件的顶部我有 [ import $ from 'jquery'; ].在我的 functions.php 中,我有我的 wp_enqueue_script 函数与数组的依赖关系('jquery'),但是当我加载时我仍然得到一个未捕获的语法错误:该 js 文件中第一行的意外标识符页面。
我在我正在使用的本地 WP 站点上有相同的设置,并且在那里工作得很好。我错过了什么?
在functions.php
function asset_files() {
wp_enqueue_script('search-jsfile', get_theme_file_uri('/js/live-search.js'), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'asset_files');
这是我的代码的开头
class Search {
constructor() {
this.openButton = $("#search-icon-btn");
this.closebutton = $(".search-overlay__close");
this.searchOverlay = $(".search-overlay");
this.events();
}
events() {
this.openButton.on("click", this.openOverlay);
this.closebutton.on("click", this.closeOverlay);
}
openOverlay() {
this.searchOverlay.addClass("search-overlay--active");
}
closeOverlay() {
this.searchOverlay.removeClass("search-overlay--active");
}
}
var liveSearch = new Search();
jQuery 是 WordPress 核心的一部分。您不需要导入它两次。
只需删除 live-search.js 文件中的 import $ from 'jquery';
。
此外,import
语句是 ES6 特性的一部分。
要使 ES6 模块在浏览器中工作,您应该将 type="module"
添加到脚本标记中,如下所示:
<script type="module" src="filename.js"></script>
我在位于 /mytheme/js/live-search.js 的自定义 js 文件中编写了一些代码 在 js 文件的顶部我有 [ import $ from 'jquery'; ].在我的 functions.php 中,我有我的 wp_enqueue_script 函数与数组的依赖关系('jquery'),但是当我加载时我仍然得到一个未捕获的语法错误:该 js 文件中第一行的意外标识符页面。
我在我正在使用的本地 WP 站点上有相同的设置,并且在那里工作得很好。我错过了什么?
在functions.php
function asset_files() {
wp_enqueue_script('search-jsfile', get_theme_file_uri('/js/live-search.js'), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'asset_files');
这是我的代码的开头
class Search {
constructor() {
this.openButton = $("#search-icon-btn");
this.closebutton = $(".search-overlay__close");
this.searchOverlay = $(".search-overlay");
this.events();
}
events() {
this.openButton.on("click", this.openOverlay);
this.closebutton.on("click", this.closeOverlay);
}
openOverlay() {
this.searchOverlay.addClass("search-overlay--active");
}
closeOverlay() {
this.searchOverlay.removeClass("search-overlay--active");
}
}
var liveSearch = new Search();
jQuery 是 WordPress 核心的一部分。您不需要导入它两次。
只需删除 live-search.js 文件中的 import $ from 'jquery';
。
此外,import
语句是 ES6 特性的一部分。
要使 ES6 模块在浏览器中工作,您应该将 type="module"
添加到脚本标记中,如下所示:
<script type="module" src="filename.js"></script>