如何注册库以正确使用jQuery

时间:2019-03-31 作者:Jaron

如何从插件级别注册正确的jquery?

如果我运行此操作:

 function insertJQuery() {

               wp_deregister_script(\'jquery\');
               wp_enqueue_script(\'jquery\', \'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\', array(), null, true);

     }

  add_action(\'wp_enqueue_scripts\', \'insertJQuery\');
还有这个工作,但如果我运行这个:

    function theme_scripts() {
              wp_enqueue_script(\'jquery\');
    }

    add_action(\'wp_enqueue_scripts\', \'theme_scripts\');
然后站点中的脚本不起作用。我阅读了使用WP中安装的jquery版本。您最终如何正确使用它以确保安全?

1 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

出于兼容性原因,您应该使用jQuery的内置版本。

您只需将其排队即可:

function theme_scripts() {
    wp_enqueue_script(\'jquery\');
}
add_action(\'wp_enqueue_scripts\', \'theme_scripts\');
或者只是将其添加为脚本的依赖项:

function theme_scripts() {
    wp_enqueue_script( \'my-script\', <PATH>, array(\'jquery\'), ... );
}
add_action(\'wp_enqueue_scripts\', \'theme_scripts\');
But then... 您必须记住,jQuery是在无冲突模式下运行的,因此在脚本中,您必须通过jQuery 而不是$. 因此,您的脚本应该如下所示:

jQuery(function ($) {
    // here you can use $ sign to get jQuery, because of the param of function

    $(\'a\').click(...); // so this will work OK
});

// but here you can\'t and you have to use jQuery
jQuery(\'a\').click(...); // this will work also

$(\'a\').click(...); // but this won\'t, because there is no $ accessible here