简体   繁体   中英

Why does this variable only work inside a function?

I have a variable that is supposed to store the data-filter of what has just been clicked. It only works inside one of my click events though, and stops working when it is moved outside of the event. I'd like to make it global so I can access it anytime, but I don't understand jQuery well enough to know what the issue is.

            var filterValue = $( this ).attr('data-filter')
            //Function Doesn't work when var filterValue is located here.
            
            $('nav').on( 'click', 'a', function() {

                //This function works when var filterValue is located here.

                $('nav').find('.is-checked').removeClass('is-checked');
                $( this ).addClass('is-checked');
                if ($(this).data("filter") === 'home') {
                    $('main').find('.dim').removeClass('dim', 500);
                } else {
                    $('.cell').not('.' + filterValue).addClass('dim', 500);
                    $('main').find('.' + filterValue).removeClass('dim', 500);
                }
            });
            $('main').on( 'click', filterValue, function() {

                //This function does not work when var filterValue is located here.

                console.log(filterValue);
            });
        });

Inside of the function, this is in a different scope (Local). If you want to use the same scope, you should assign the first scope to a new variable called that or something else.

function someFunc() {
    var that = this;
    something.on("click", function() {
        console.log(_this);
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM