jQuery,从函数外部获取变量
我有以下jQuery示例:jQuery,从函数外部获取变量,jquery,variables,Jquery,Variables,我有以下jQuery示例: $('li.mega').mouseover(function() { var megaTrue = 1; }); $('li.mega').mouseout(function() { var megaTrue = 0; }); 及 function functionName() { if( megaTrue == 1 ) { //do something } else {
$('li.mega').mouseover(function() {
var megaTrue = 1;
});
$('li.mega').mouseout(function() {
var megaTrue = 0;
});
及
function functionName() {
if( megaTrue == 1 ) {
//do something
} else {
//do nothing
return false;
}
}
但是megaTrue
将是未定义的,jQuery中是否有类似全局变量的内容
非常感谢您的建议
var megaTrue=0;
$('li.mega').mouseover(function() {
megaTrue = 1;
});
$('li.mega').mouseout(function() {
megaTrue = 0;
});
可以将megaTrue设置为全局变量,但使用全局变量很少是个好主意:这在Javascript和任何地方都是如此。存储数据的语义、有意义的地方是元素本身。jQuery通过以下方法支持这一点: 如果您有许多
li.mega
元素,并且不关心鼠标移到哪个元素上,则可以在父元素上设置值:
$('li.mega').mouseover(function() {
$(this).parent().data('mousedOver', true);
}).mouseout(function() {
$(this).parent().data('mousedOver', false);
});
抱歉,错过了一个关键步骤:检查值。然后,您可以使用如下方法从元素中获取值:
if ($('li.mega').data('mousedOver')) {
仅在函数外部定义变量就可以满足您的要求。如何警告或记录变量值的更改?可以,但是如果(鼠标移动)仍然是
未定义的
。因为它在不同的功能中。考虑到这将存储在$.cache对象中,除了稍微少一些混乱(但更复杂的代码)之外,还有什么好处?或者我是否需要检查.data
中的鼠标移动器
?如果是,如何设置?@NewUser这是因为它没有设置全局值:请参阅我的编辑。@lonesomeday-是的,我知道缺少了一些内容。谢谢你的帮助。
if ($('li.mega').data('mousedOver')) {