如何在 Wordpress 中正确使用 jQuery 脚本


How to properly use jQuery scripts in Wordpress?

我觉得我在这里肯定错过了一些简单的东西...... 但对于我的生活,找不到我错过的东西。

我有"坏习惯",将jQuery函数直接包含在头文件.php文件中(以及其他位置(。 据我了解,这是不受欢迎的,函数应该保存在一个单独的文件中,使用 wp_enqueue 函数加载它们(如果我理解正确的话(。

我正在尝试遵循此处给出的解决方案:如何将一个简单的jQuery脚本添加到WordPress?

我的标题中有这个简单的函数.php应该在准备好的文档时触发:

<script>
    // Scroll to Top
    jQuery(document).ready(function () {
        // Force element to hidden state when page loads
        jQuery('.scroll-to-top').hide();
        // Check to see if the window is top if not then display button
        jQuery(window).scroll(function () {
            if (jQuery(this).scrollTop() > 200) {
                jQuery('.scroll-to-top').fadeIn();
            } else {
                jQuery('.scroll-to-top').fadeOut();
            }
        });
        //Click event to scroll to top
        jQuery('.scroll-to-top').click(function () {
            jQuery('html, body').animate({ scrollTop: 0 }, 800);
            return false;
        });
    });
</script>

因此,为了"正确"地做事,我将代码取出并放在myScripts中.js(当然要删除脚本标签(。 在我的函数.php文件中,我添加了以下代码:

<?php
    function add_my_script() {
        wp_enqueue_script(
            'myScripts', // name your script so that you can attach other scripts and de-register, etc.
            get_template_directory_uri() . '/js/myScripts.js', // this is the location of your script file
            array('jquery') // this array lists the scripts upon which your script depends
        );
    }
    add_action( 'wp_enqueue_scripts', 'add_my_script' );
?>

但是当我加载我的页面时,脚本不再工作。

编辑

感谢您到目前为止的帮助... 更改此行:

add_action( 'wp_enqueue_scripts', 'myScripts' );

对此:

add_action( 'wp_enqueue_scripts', 'add_my_script' );

解决了页面上看到的错误。

不幸的是,代码似乎不再在页面上触发。 我假设因为它是(document(.ready,它应该自动触发(就像我直接包含它时一样(,但是当我以这种方式包含脚本时它不会。 呸。。。 思潮?

请参阅wp_enqueue_script文档

wp_enqueue_script($handle、$src、$deps、$ver、$in_footer(是正确的函数。

第一个参数必须是回调函数名称。