11

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

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');
4

4 回答 4

22

您的wp_enqueue_script.

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以获取"Hey! You have clicked the button!"消息。

于 2013-04-15T09:41:32.067 回答
4

您也可以尝试本地化 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')
    )
);

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

于 2015-05-07T08:28:37.820 回答
0

Place the code block below the wp_enqueue_script    

Then Add it as a variable on your custom script. Here is called "custom-js"

    var dir_url = adact_img.dir_url;
       $('hello') .owlCarousel({
                items: 1,
                loop: true,
                margin: 0,
                dots: false,
                nav: true,
                navText: ["<img src='"+ dir_url +" /assets/images/icons/angle-right.png' />", "<img src='"+ dir_url +" /assets/images/icons/angle-left.png' />"],
            });


        
于 2021-04-05T03:38:18.560 回答
0
Place the code block below the wp_enqueue_script    



     $dir_url = array( 'dir_url' => get_stylesheet_directory_uri() );
        wp_localize_script( 'custom-js', 'adact_img', $dir_url );



Then Add it as a variable on your custom script. Here is called "custom-js"

    var dir_url = adact_img.dir_url;
       $('hello') .owlCarousel({
                items: 1,
                loop: true,
                margin: 0,
                dots: false,
                nav: true,
                navText: ["<img src='"+ dir_url +" /assets/images/icons/angle-right.png' />", "<img src='"+ dir_url +" /assets/images/icons/angle-left.png' />"],
            });


        
于 2021-04-05T03:39:23.850 回答