我使用 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 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 .
关于javascript - 是否可以将变量的值从一个 javascript 导出到另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1305345/