javascript - 如何将 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");
});
});
解决方案
只是@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
作为参数传递,将在函数中用作$
. 这样您就可以使用您已经习惯的语法。
推荐阅读
- javascript - Tabulator.js:单击复选框时不会触发 cellClick 回调
- ios - 快速正则表达式检查字符串是否为金额格式(2x,3x,...)
- javascript - 我将如何为幻灯片添加自动化?
- domain-driven-design - DDD 建模聚合,不变量少,字段多
- linux - 如何使用行号 bash 脚本将文件中的特定行替换为字符串变量?
- linux - scp从远程到本地时如何正确构造本地文件夹的路径
- next.js - Tailwind + NextJS 某些类在运行构建脚本时不起作用
- javascript - 禁用缓存时未触发浏览器 SecurityPolicyViolation 事件
- prolog - DCG:隐藏在所有规则中的争论?
- typescript - 如何在 Typescript Playground 中显示控制台输出