如何向 WordPress 添加一个简单的 jQuery 脚本? [英] How do I add a simple jQuery script to WordPress?
问题描述
我阅读了 Codex 和一些关于在 WordPress 中使用 jQuery 的博客文章,这非常令人沮丧.我已经在 functions.php
文件中加载了 jQuery,但是所有的指南都很糟糕,因为它们假设您已经拥有大量的 WordPress 经验.例如,他们说现在我正在通过 functions.php
文件加载 jQuery,现在我要做的就是加载我的 jQuery.
I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I've got as far as loading jQuery in functions.php
file, but all of the guides out there are crappy because they assume you already have a ton of WordPress experience. For instance, they say that now that I'm loading jQuery through the functions.php
file, now all I have to do is load my jQuery.
我究竟该怎么做?具体来说,我应该向哪些文件添加代码?我究竟如何为单个 WordPress 页面添加它?
How exactly do I do this? What files, specifically, do I add code to? How exactly do I add it for a single WordPress page?
推荐答案
我知道您对教程的意思.这是我的做法:
I know what you mean about the tutorials. Here's how I do it:
首先,您需要编写脚本.在您的主题文件夹中创建一个名为js"的文件夹.在该文件夹中为您的 javascript 创建一个文件.例如.你的脚本.js.将您的 jQuery 脚本添加到该文件(您不需要在 .js 文件中使用 标签).
First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need <script>
tags in a .js file).
以下是您的 jQuery 脚本(在 wp-content/themes/your-theme/js/your-scrript.js 中)的外观示例:
Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:
jQuery(document).ready(function($) {
$('#nav a').last().addClass('last');
})
请注意,我在函数的开头使用了 jQuery 而不是 $.
Notice that I use jQuery and not $ at the start of the function.
好的,现在打开主题的functions.php文件.您需要使用 wp_enqueue_script()
函数,这样您就可以添加脚本,同时告诉 WordPress 它依赖于 jQuery.操作方法如下:
Ok, now open your theme's functions.php file. You'll want to use the wp_enqueue_script()
function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
假设您的主题在正确的位置有 wp_head 和 wp_footer,这应该可以工作.如果您需要更多帮助,请告诉我.
Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.
WordPress 问题可以在 WordPress Answers 提出.
WordPress questions can be asked over at WordPress Answers.
这篇关于如何向 WordPress 添加一个简单的 jQuery 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!