jQuery-从另一个函数抓取变量 [英] Jquery - Grab Variable from Another Function
问题描述
我的页面上有两个功能.我试图找到一种方法来访问函数2中的函数1中的变量:
$(function() {
$('a[id=1]').live("click", function(event) {
event.preventDefault();
var Var1 = "something1";
});
});
$(function() {
$('a[id=2]').live("click", function(event) {
event.preventDefault();
var Var2 = event.var1;
});
});
因此,我确定上面的内容是错误的,但是您可以看到在函数2中我如何尝试从第一个函数中获取变量.
有没有办法做到这一点?我不知道为什么,但是我一直认为它与event.var1
或事件功能有关.
您需要在两个函数都可以访问的范围内声明变量.我建议将您的两个文档就绪处理程序合并为一个函数,并在其中声明变量:
$(function() {
var var1; // may want to assign a default
$('a[id=1]').live("click", function(event) {
event.preventDefault();
var1 = "something1";
});
$('a[id=2]').live("click", function(event) {
event.preventDefault();
var var2 = var1;
});
});
或者,如果您也需要从其他位置访问变量,则可以将其设置为全局变量.
请注意,这两个单击事件彼此无关,因此它们当然不会共享事件数据.另外,在单击第二个锚点之前可能先单击第二个锚点,所以您可能想给var1
一个默认值和/或测试undefined
,然后在第二个点击处理程序中使用它.
(而且我已经将Var1
更改为var1
,因为JS约定是用小写字母开头的变量名-您不必遵循约定,但我建议这样做.)>
I have two functions on my page. I am trying to find a way to access a variable in function 1 inside function 2:
$(function() {
$('a[id=1]').live("click", function(event) {
event.preventDefault();
var Var1 = "something1";
});
});
$(function() {
$('a[id=2]').live("click", function(event) {
event.preventDefault();
var Var2 = event.var1;
});
});
So I am sure my above is incorrect but you can see how in function 2 I am trying to grab a variable from the first function.
Is there a way I can do this? I don't know why, but I keep thinking it has something to do with the event.var1
or the event functionality.
You need to declare the variable outside both functions, in a scope they can both access. I suggest combining your two document ready handlers into a single function and declaring the variable there:
$(function() {
var var1; // may want to assign a default
$('a[id=1]').live("click", function(event) {
event.preventDefault();
var1 = "something1";
});
$('a[id=2]').live("click", function(event) {
event.preventDefault();
var var2 = var1;
});
});
Or you could make the variable a global if you need to access it from other places too.
Note that the two click events have nothing to do with each other so they certainly don't share event data. Also, a click on the second anchor may occur before a click on the first, so you may want to give var1
a default value and/or test for undefined
befor using it inside the second click handler.
(Also I've changed Var1
to var1
because the JS convention is to start variable names with a lowercase letter - you don't have to follow the convention, but I'd recommend it.)
这篇关于jQuery-从另一个函数抓取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!