首页 > 解决方案 > 如何将 JavaScript 代码添加到 wordpress 中的 js 文件中

问题描述

如何将javascript代码添加到.js文件并添加到wordpress中的function.php?我有那个 js 代码,我将该代码添加到一个 .js 文件中,并通过 wp_enqueue_script() 函数在 function.php 中使用它,但它没有加载。

 $(document).ready(function () {
        //  When user clicks on tab, this code will be executed
        $(".mtabs li").click(function () {
            //  First remove class "active" from currently active tab
            $(".mtabs li").removeClass('active');

            //  Now add class "active" to the selected/clicked tab
            $(this).addClass("active");

            //  Hide all tab content
            $(".mtab_content").hide();

            //  Here we get the href value of the selected tab
            var selected_tab = $(this).find("a").attr("href");

            //  Show the selected tab content
            $(selected_tab).fadeIn();

            //  At the end, we add return false so that the click on the link is not executed
            return false;
        });
        $("#simulate").click(function () {
            $('a[rel="tab2"]').trigger("click");
        });
    });

标签: javascriptphpwordpress

解决方案


只是@mash-r 答案的改进/不同方法

在像这样使用带有 wp_enqueue_script 的 jQuery 依赖项之后wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true);

jQuery您可以将其包装在IIFE(立即调用函数表达式 - (function(){})();)中,而不是重复所有代码

(function ($) {
    $(document).ready(function () {
        $(".mtabs li").click(function () {
            //  First remove class "active" from currently active tab
            $(".mtabs li").removeClass('active');

            //  Now add class "active" to the selected/clicked tab
            $(this).addClass("active");

            //  Hide all tab content
            $(".mtab_content").hide();

            //  Here we get the href value of the selected tab
            var selected_tab = $(this).find("a").attr("href");

            //  Show the selected tab content
            $(selected_tab).fadeIn();

            //  At the end, we add return false so that the click on the link is not executed
            return false;
        });
        $("#simulate").click(function () {
            $('a[rel="tab2"]').trigger("click");
        });
    });
})(jQuery);

这将jQuery作为参数传递,将在函数中用作$. 这样您就可以使用您已经习惯的语法。


推荐阅读