如何在WordPress中添加简单的jQuery脚本? [英] How do I add a simple jQuery script to WordPress?

查看:136
本文介绍了如何在WordPress中添加简单的jQuery脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了Codex和一些有关在WordPress中使用jQuery的博客文章,这非常令人沮丧.我已经尽力将jQuery加载到functions.php文件中,但是那里的所有指南都很糟糕,因为它们假定您已经具有大量的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创建一个文件.例如. your-script.js.将jQuery脚本添加到该文件(.js文件中不需要<script>标记).

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 questions can be asked over at WordPress Answers.

这篇关于如何在WordPress中添加简单的jQuery脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆