简体   繁体   English

如何在另一个函数中访问javascript自定义全局变量

[英]how to access javascript custom global variable in another function

I have developing phonegap android application. 我正在开发phonegap android应用程序。 I'm trying to establish the communication between javascript and android java classes. 我正在尝试在javascript和android java类之间建立通信。

For Communication i have used addJavaScriptInterfaceMethod in android main activity.So that i can use java object and method in javascript. 为了进行通信,我在android main activity中使用了addJavaScriptInterfaceMethod。以便可以在javascript中使用java对象和方法。

following is the Java Code : 以下是Java代码:

 public class Activity extends DroidGap
  {
       @Override
       public void onCreate(Bundle savedInstanceState) 
       {

            super.onCreate(savedInstanceState);
            setIntegerProperty("loadUrlTimeoutValue", 60000);
            super.loadUrl("file:///android_asset/www/jq3.html");
            MapTablesWrapper table = new MapTablesWrapper();
            super.appView.addJavascriptInterface(new MapTablesWrapper(), "tables");

           }
     }

And in javascript :the following code does not printing the table value.It's alerting undefined 并且在javascript中:以下代码不打印表值。它警告未定义

var tableName = tables.getTableName();
function(){
       alert(tableName);

 }

And if i declare var table inside the function.Its printing the tableName and following code is 如果我在函数内部声明var table,它会打印tableName和以下代码是

 function(){
       var table = tables.getTableName();
       alert(tableName);
 }

But i would like to declare variable outside of the function and want to use that varaible in inside the function. 但是我想在函数外部声明变量,并想在函数内部使用该变量。

You can do like 你可以喜欢

var global = {
    table : null
};

function()
{
   global.table = tables.getTableName();
   alert(global.table);
}

you can rename global as your JS file name, so that this variable can be accessed all the functions in the current file and also in any other JS File by using your fileName.table here it is global.table 您可以将global重命名为您的JS文件名,以便使用您的fileName.table可以访问当前文件以及任何其他JS文件中的所有函数,此处为global.table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM