简体   繁体   中英

Variable is undefined whereas it defined

The code below gives an undefined error on console for the variable mystyle . I don't get it as i defined the variable.

jQuery( '.styles_div' ).each( function() {
switch (styles) {
    case 'style1':
        var mystyle = $('#stylewrap').append('<div class="style1"></div> ');
        break;
    case 'style2':
        var mystyle = $('#stylewrap').append('<div class="style2"></div> ');
        break;
}
$("#search").autocomplete({
    delay: 0,
    minLength: 3,
    search: function( event, ui ) {mystyle.show();},
    ...
})
});

mystyle needs to be defined before it is used - perhaps as a global var and not have the var keyword twice. It is also prudent to test the existence

var mystyle;
switch (styles) {
    case 'style1':
        mystyle = $('#stylewrap').append('<div class="style1"></div> ');
        break;
    case 'style2':
        mystyle = $('#stylewrap').append('<div class="style2"></div> ');
        break;
}
$("#search").autocomplete({
    delay: 0,
    minLength: 3,
    search: function( event, ui ) {if (mystyle) mystyle.show();},
    ...
})

if this is the complete code, then perhaps this code is simpler:

var mystyle = $('#stylewrap').append('<div class="'+styles+'"></div> ');

Define mystyle before switch case . otherwise the code is correct.

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