传递一个值并在javascript中打印

时间:2016-06-24 13:23:31

标签: javascript

我试图在我的js文件中传递一个lang变量。

其实我有这个:

<script src="assets/js/plugins.js?lang=en"></script>

plugins.js中,我有这个:

var LIBS = {
    // Chart libraries
    validation: [
        "assets/libs/validation/jquery.validation.min.js",
        "assets/libs/validation/lang/xxxxxx.min.js"
    ],
    ...
};

如何通过lang lang传递xxxxxx值来替换en

感谢。

3 个答案:

答案 0 :(得分:0)

plugin.js

中尝试此操作

var LIBS = {
    // Chart libraries
    validation: [
        "assets/libs/validation/jquery.validation.min.js",
        "assets/libs/validation/lang/xxxxxx.min.js"
    ]
};
LIBS.tmpValidation = LIBS.validation;
LIBS.validation = [];
LIBS.lang = "en";
Object.defineProperty(LIBS, "validation", {
  get : function(){
    var self = this;
    return this.tmpValidation.map(function(item){
      return item.replace(/xxxxxx/g, self.lang)
    })
  }
});
console.log(LIBS.validation);

您现在可以在调用lang之前将LIBS属性设置为LIBS.validation的方式定义插件

答案 1 :(得分:-1)

var s = document.getElementsByTagName('script'),
    ss = s[s.length-1];
    lang = ss.src.match(/\?lang=(\w\w)/);
// sure...  check it exists!
console.debug(lang[1]);

在plugins.js里面

答案 2 :(得分:-1)

您可以使用全局变量。

全局变量:

我在这里使用了一个对象来存储设置,如果你愿意,可以添加更多设置

var settings = { lang:'en' };

您的其他脚本(plugins.js):

var LIBS = {
    // Chart libraries
    validation: [
        'assets/libs/validation/jquery.validation.min.js',
        'assets/libs/validation/lang/' + settings.lang + '.min.js'
    ],
    ...
};

这是一个完整的示例脚本,它正是我正在讨论的内容。我已经在同一个脚本中声明了LIBS,但它可以很容易地包含在plugins.js中,并在此脚本中的全局设置变量设置下面声明...

示例脚本:

<script>
    var settings = { lang:'en' };
    console.log(settings); // Show that the value has been set.

    var LIBS = {
        // Chart libraries
        validation: [
            'assets/libs/validation/jquery.validation.min.js',
            'assets/libs/validation/lang/' + settings.lang + '.min.js'
        ]
    };

    // Show that LIBS has been set with the language setting from the global variable.
    console.log(LIBS);
</script>

运行完之后,您将看到变量已被拾取并且数组中的第二个条目为assets/libs/validation/lang/en.min.js

或者更接近你自己的榜样......

<script>
    var settings = { lang:'en' };
    console.log(settings); // Show that the value has been set.
</script>
<!-- Following line must come after the script above
     this JS file can now access that global settings variable -->
<script src="plugins.js"></script>