无法理解如何在WordPress中正确加入jQuery [英] Having trouble understanding how to properly enqueue jQuery in WordPress

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

问题描述

因此,按照建议,我将脚本排入function.php文件,而不是像下面的示例那样排入头部:

So as recommended, I enqueue my scripts in the function.php file instead of in the head like the following example:

function bok_scripts() {
    wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js' );
}
add_action( 'wp_enqueue_scripts', 'bok_scripts' );

问题是,除非我使用通常的方法将jQuery添加到头部,否则此JavaScript将无法工作:

The problem is that this JavaScript won't work unless I add jQuery to the head using the usual:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我经常遇到的问题是,WordPress使用wp-admin/includes目录中的wp_head();自动加载jQuery版本.因为jQuery正在加载2倍,所以它破坏了一些代码.例如,以下将引发这不是函数($)"错误:

The problem I always run into, though, is that WordPress automatically loads a version of jQuery using the wp_head(); from the wp-admin/includes directory. Because the jQuery is getting loaded 2x, it breaks some of the code. For instance the following will throw a 'This is not a function ($)' error:

$(window).load(function(){
    $('#modal-notices').modal('show');
});

有人知道如何克服这个问题吗?我已经尝试了很多东西,但是似乎所有的工作都是从wp-admin/includes目录中删除jQuery.显然,这不是一个正确的解决方法.

Does anyone know how to overcome this? I've tried a bunch of stuff, but all that seems to work is deleting the jQuery from the wp-admin/includes directory. Obviously, though, that isn't a proper fix.

推荐答案

您需要做的第一件事是将jQuery声明为脚本的依赖项,以便WordPress知道要加载它.

The first thing you need to do is declare jQuery as a dependency of your script so that WordPress knows to load it.

要进行更改,请执行以下操作:

To do that change:

wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js' );

收件人:

wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ) );

您面临的第二个问题是,WordPress在WordPress中以noConflict模式加载.这意味着全局"$"快捷方式不再可用.以下是更多信息: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

There's a second issue you're facing and that's jQuery in WordPress loads in noConflict mode. This means the global '$' shortcut is no longer available. Here's some more information: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

要更改脚本的工作方式,请执行以下操作:

To get your script working change:

$(window).load(function(){
    $('#modal-notices').modal('show');
});

收件人:

(function($) {
    $(window).load(function(){
        $('#modal-notices').modal('show');
    });
})(jQuery);

最后,请确保删除直接添加到页眉/页脚而不是排队的所有jQuery脚本.

Finally be sure to remove any jQuery scripts you've added directly to the header/footer instead of enqueueing.

这篇关于无法理解如何在WordPress中正确加入jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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