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

我使用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);} }); }); 

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

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

编辑:

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

全局变量

在函数之外声明变量之类的

 var myVariable; 

要么

 myVariable; 

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

 function firstFunction() { // Local scope ie scoped to firstFunction var localVariable; // Global scope ie 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 } 

这种情况的不同之处在于,警报将失败并且在执行secondFunction()之前不会显示globalVariable的值, globalVariable执行secondFunction() ,因为这是声明变量的地方。 如果变量已在任何函数之外声明,则警报将成功并显示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); } 

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

请查看此工作演示以获取更多详细信息。

出于不使用全局变量的原因,请查看本文 。

是否必须使用JavaScript变量?

您可以使用.data()函数存储相关元素的信息吗?