是否可以将变量的值从一个javascript导出到另一个?

时间:2009-08-20 10:47:49

标签: javascript jquery variables export

我使用jquery和php制作了一个网页,其中所有文件都以模块化的方式使用。现在我有两个必须相互通信的JavaScript文件。一个脚本生成一个包含数字的变量( id_menu_bar )。我希望这个变量被传输到第二个JavaScript并在那里使用。

我该怎么做?

这里是剧本

menu_bar.js

$(document).ready(function() {

function wrapper_action(id_menu_bar) {
  $(".wrapper").animate({height: "0px"});
  $("#changer p").click(function() {
    $(".wrapper").animate({height: "300px"});
  });
}

  $("#select_place li").live("click", function() {
  var wrapper_id = $(".wrapper").attr("id");
  var id_place = this.id;

  if (wrapper_id != "place")
    {
    $("#select_level li").remove();
      $("#select_building").load("menu_bar/menu_bar_building.php?placeitem="+id_place, function() {
        $("#select_building li").click(function() {
        var id_building = this.id;

          if (wrapper_id != "building")
            {
            $("#select_level").load("menu_bar/menu_bar_level.php?buildingitem="+id_building, function() {
              $("#select_level li").click(function() {
                var id_level = this.id;
                wrapper_action(id_level);
              });
            });

            }
          else if (wrapper_id == "building")
            {wrapper_action(id_building);}
        });
      });

      }
   else if (wrapper_id == "place")
    {wrapper_action(id_place);}
   });

}); 

2 个答案:

答案 0 :(得分:5)

如果变量id_menu_bar在全局范围内,那么它可以被页面上的另一个脚本使用。

jQuery的$.data()也适用于存储数据元素,这意味着您不需要使用全局变量并污染全局命名空间。

修改

在回复您的评论时,您声明变量的方式会有所不同,这些变量决定了它们在JavaScript中的作用域。

全局变量

在声明像

之类的变量的函数之外
var myVariable;

myVariable;

没有区别 - 两个变量都具有全局范围。事实上,第二种方法将给出一个可变的全局范围,甚至在函数内部。例如

function firstFunction() {
    // Local scope i.e. scoped to firstFunction
    var localVariable; 

    // Global scope i.e. available to all other JavaScript code running
    // in the page
    globalVariable = "I'm not really hiding";
}

function secondFunction() {
    // I can access globalVariable here but only after
    // firstFunction has been executed
    alert(globalVariable); // alerts I'm not really hiding
}

此方案的不同之处在于警报将失败,并且在globalVariable执行secondFunction()之后不会显示firstFunction()的值,因为这是变量所在的位置声明。如果变量已在任何函数之外声明,则警报将成功并显示globalVariable的值

使用jQuery.data()

使用此命令,可以将数据存储在元素的缓存对象中。我建议查看源代码,了解它是如何实现的,但它非常整洁。考虑

  function firstFunction() {
      $.data(document,"myVariable","I'm not really hiding"); 
      globalVariable = "I'm not hiding";
  }

  function secondFunction() {
      // alerts "I'm not really hiding" but only if firstFunction is executed before
      // secondFunction
      alert($.data(document, "myVariable"));

      // alerts "I'm not hiding" but only if firstFunction is executed before
      // secondFunction
      alert(globalVariable);
  }

在这种情况下,使用"I'm not really hiding"中的密钥字符串myVariable对文档对象存储字符串值firstFunction。然后,可以从脚本中任何其他位置的缓存对象中检索此值。尝试从缓存对象中读取值而不先设置它将产生undefined

有关详细信息,请查看此 Working Demo

出于不使用全局变量的原因,请查看此article

答案 1 :(得分:0)

是否必须是JavaScript变量?

您可以使用.data()功能针对相关元素存储信息吗?