我在主题functions.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');
您没有在wp_enqueue_script中包含任何javascript文件.
原文链接:https://www.f2er.com/php/133379.htmlfunction pw_load_scripts() { wp_enqueue_script('pw-script',get_template_directory_uri() . '/test.js'); wp_localize_script('pw-script','pw_load_scripts');
如果您再查看源代码,您会看到:
<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以获取“嘿!您已单击按钮!”信息.