【问题标题】:jQuery not loading into custom js file in WordPressjQuery 未加载到 WordPress 中的自定义 js 文件中
【发布时间】:2019-08-28 07:03:47
【问题描述】:

我正在 /mytheme/js/live-search.js 中的自定义 js 文件中编写一些代码 在 js 文件的顶部,我有 [ import $ from 'jquery'; ]。在我的functions.php中,我的wp_enqueue_script函数具有array('jquery')的依赖关系,但是当我加载页面时,我仍然得到一个Uncaught SyntaxError:该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 loading


    【解决方案1】:

    jQuery 是 WordPress 核心的一部分。您无需导入两次。

    只需在您的 live-search.js 文件中删除 import $ from 'jquery';


    另外,import 语句是 ES6 功能的一部分。

    要使 ES6 模块在浏览器中工作,您应该像这样将 type="module" 添加到脚本标签:

    <script type="module" src="filename.js"></script>
    

    【讨论】:

    • 嘿安德鲁,我之前试过一次,当它遇到我的第一个构造函数语句“this.openButtun = $(”#search-icon -btn");"
    • 嘿帕特里克,试着把它放在你的 js 文件中:(function($) { /* Your code inside here; */ })(jQuery);
    • 感谢您的快速回复!这适用于我的构造函数语句,但在事件部分它向我抛出了一个“Uncaught TypeError: Cannot read property 'on'”错误,前几个这样的语句“this.openButton.on(”click", this .openOverlay);"..... :( 我最终要声明我想使用的每个 jquery 函数吗?
    • 错误到底是什么意思?无法读取“on”属性...? this.openButton 是 jQuery 对象吗?
    • 抱歉,完整的错误是“Uncaught TypeError: Cannot read property 'on' of undefined”我在代码开头更新了我的原始问题。
    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2014-12-26
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多