【问题标题】:How can I pass variables to external javascript file that can be accessed by all the functions如何将变量传递给所有函数都可以访问的外部 javascript 文件
【发布时间】:2016-06-14 19:01:54
【问题描述】:

我有一个 Kendo 网格,它的 Events 属性与外部 javascript 文件中的函数 (Grid_OnRowSelect) 挂钩。外部 javascript 文件中还有其他功能(例如 on button click * $("#btnS").on('click', function () {....* )和其他一些功能。 Grid_OnRowSelect 函数和其他函数使用公共变量集。如何将变量从所有函数都可以访问的视图 (cshtml) 传递到外部 javascript 文件。

@(Html.Kendo().Grid<MyModel>()
.Name("rGrid")
.Events(events => events.Change("Grid_OnRowSelect"))
.Columns(columns =>
{
    columns.Command(command =>

 .......
 .......
 .......

外部js文件是

var MYFunc = MYFunc || (function () {
var _args = {}; // private

return {
    init: function (Args) {
        _args = Args;
        // some other initialising
    },
    helloWorld: function () {
        alert('Hello World! -' + _args[0]);
    },
    Grid_OnRowSelect: function (e) {

        var data = this.dataItem(this.select());
        detailRequestID = data.ID;

        var url = _args[1] + "/" + detailRequestID;
        window.location.href = url;
    },
    onError: function (e, status) {
        //alert("A server error has occurred!");
        var url = _args[2];
        window.location.href = url;

    }
};

}());

我如何尝试传递参数

  <script>
    window.onload = function(){
    var searchUrl = @Url.Action("Search");
    var updateUrl = @Url.Action("Update");
    var errorUrl = @Url.Action("ServerError", "Error");
};
MYFunc.init([searchUrl, updateUrl, errorUrl]);</script><script src="~/Scripts/Index.js"></script>

但是当 Grid_OnRowSelect 或任何函数被执行时,_args 是未定义的。什么不正确?

谢谢。

【问题讨论】:

    标签: javascript jquery kendo-ui kendo-asp.net-mvc external-js


    【解决方案1】:

    如果您只是在 javascript 中的函数之外声明一个变量,那么在它之后加载的所有代码 JS 代码都可以使用该变量。文件是外部的这一事实并不重要,只是它在您设置全局变量的位置之后加载到 DOM 中。

    例子

    var globalVar = "I am global";
    function test(){
        var copy = globalVar;//copy now == "I am global"
        var nonglobalVar = "I am not";//this is local to the function
    }
    var global2 = globalVar;//global2 now == "I am global"
    var anotherVar = nonglobalVar;//this line will throw an error because variable is out of scope.
    

    另一种常见的策略是将您的值写入 html 中的隐藏字段,然后从您的外部函数访问它。

    【讨论】:

      猜你喜欢
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2014-06-17
      • 1970-01-01
      相关资源
      最近更新 更多