开发者

jQuery, get variable from outside of the function

I have following jQuery example:

$('li.mega').mouseover(function() {
    var megaTrue = 1;
});

$('li.mega').mouseout(function() {
    var megaTrue = 0;
});

and than

function functionName() {

        if( megaTrue == 1 ) {

             //do something

        } else {

            //do 开发者_StackOverflownothing
            return false;   

        }               
    }

But megaTrue will be undefined, is there something like a GLOBAL variable in jQuery?

All suggestion much appreciated.


var megaTrue=0; 
$('li.mega').mouseover(function() { 
    megaTrue = 1; 
}); 

$('li.mega').mouseout(function() { 
    megaTrue = 0; 
}); 

set megaTrue as a global var


You can, but it's very rarely a good idea to use globals: this is true in Javascript as much as anywhere. The semantic, meaningful place to store data is with the element itself. jQuery supports this with the data method:

$('li.mega').mouseover(function() {
    $(this).data('mousedOver', true);
}).mouseout(function() {
    $(this).data('mousedOver', false);
});

If you have many li.mega elements and you don't care which one is moused over, you could set the value on the parent element:

$('li.mega').mouseover(function() {
    $(this).parent().data('mousedOver', true);
}).mouseout(function() {
    $(this).parent().data('mousedOver', false);
});

Sorry, missed a crucial step: checking the value. You can then get the value off the element using the data method like this:

if ($('li.mega').data('mousedOver')) {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜