个性化阅读
专注于IT技术分析

wp_localize_script不起作用

点击下载

我的主题函数.php中有以下代码, 但是当我调用console.log(pw_script_vars);时, 变量未定义。我错过了什么?

function mytheme_enqueue_scripts(){
    wp_enqueue_script( 'jquery' );

}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts');

function pw_load_scripts() {

    wp_enqueue_script('pw-script');
    wp_localize_script('pw-script', 'pw_script_vars', array(
            'alert' => __('Hey! You have clicked the button!', 'pippin'), 'message' => __('You have clicked the other button. Good job!', 'pippin')
        )
    );


}
add_action('wp_enqueue_scripts', 'pw_load_scripts');

#1


你的wp_enqueue_script中没有包含任何javascript文件。

function pw_load_scripts() {

    wp_enqueue_script('pw-script', get_template_directory_uri() . '/test.js');
     wp_localize_script('pw-script', 'pw_script_vars', array(
            'alert' => __('Hey! You have clicked the button!', 'pippin'), 'message' => __('You have clicked the other button. Good job!', 'pippin')
        )
    );


}
add_action('wp_enqueue_scripts', 'pw_load_scripts');

在主题目录中创建一个名为test.js的空文件, 它将起作用。

如果你随后查看源代码, 则会看到:

<script type='text/javascript'>
/* <![CDATA[ */
var pw_script_vars = {"alert":"Hey! You have clicked the button!", "message":"You have clicked the other button. Good job!"};
/* ]]> */
</script>

然后, 你可以在控制台中键入pw_script_vars.alert以获得”嘿!你已经单击了按钮!”信息。


#2


你也可以尝试本地化jQuery, 而无需创建其他空JS文件。

    wp_localize_script('jquery', 'pw_script_vars', array(
        'alert' => __('Hey! You have clicked the button!', 'pippin'), 'message' => __('You have clicked the other button. Good job!', 'pippin')
    )
);

对我来说, 它就像是一种魅力。希望能帮助到你。

赞(0)
未经允许不得转载:srcmini » wp_localize_script不起作用

评论 抢沙发

评论前必须登录!