脚本本地化不起作用

时间:2016-07-13 作者:anton

我不明白在wordpress中脚本本地化是如何工作的。我用php创建了一个关联数组:

$translations = array(
    \'value1\'  =>\'This is first value\',
    \'value2\'  =>\'This is second value\'
    ); 
我创建了简单的javascript文件,我想在其中使用这个数组:

jQuery(document).ready(function($){
    alert(translations);
});
然后,我尝试在插件中排队并本地化此javascript文件,如下所示:

function kvkoolitus_load_comment_validation(){
  wp_enqueue_script( \'simple-js\', plugin_dir_url( __FILE__ ) . \'js/jquery.simple.js\', array(\'jquery\'), \'\', true );
  wp_localize_script( \'simple-js\', \'translations\', $translations );
}

add_action( \'wp_enqueue_scripts\', \'kvkoolitus_load_comment_validation\' );
但当我加载带有此javascript文件的页面时,警报会告诉我“translations”对象为null
我错过了什么?

1 个回复
最合适的回答,由SO网友:czerspalace 整理而成

从答案中复制here regarding variable scope

Variables inside a function are only available inside that function. 
Variables outside of functions are available anywhere outside of functions, 
but not inside any function.
因此,您需要添加$translations 中的数组kvkoolitus_load_comment_validation 功能,如

function kvkoolitus_load_comment_validation(){
  $translations = array(
    \'value1\'  =>\'This is first value\',
    \'value2\'  =>\'This is second value\'
  ); 
  wp_enqueue_script( \'simple-js\', plugin_dir_url( __FILE__ ) . \'js/jquery.simple.js\', array(\'jquery\'), \'\', true );
  wp_localize_script( \'simple-js\', \'translations\', $translations );
}

add_action( \'wp_enqueue_scripts\', \'kvkoolitus_load_comment_validation\' );