如何使用超时添加类

Luk*_*kas 2 javascript jquery timeout addclass removeclass

不知道为什么它不起作用,我认为代码很好 - 你能告诉我什么是错的吗?我需要在一段时间间隔之后添加一些课程......

$('.main_menu ul li').mouseenter(function(){
    setTimeout(function(){
        $(this).children('.sub_menu_main').addClass('opened')
    },200);
});
$('.main_menu ul li').mouseleave(function(){
    $(this).children('.sub_menu_main').removeClass('opened')
});
Run Code Online (Sandbox Code Playgroud)

ade*_*neo 5

$('.main_menu ul li').on({
    mouseenter: function(){
        var self = this; //in scope
        $(self).data('timer', setTimeout(function(){ //new scope
            $(self).children('.sub_menu_main').addClass('opened'); //out of scope
        },200);
    },
    mouseleave: function(){
        clearTimeout($(this).data('timer'));
        $(this).children('.sub_menu_main').removeClass('opened');
    }
});
Run Code Online (Sandbox Code Playgroud)