jqury中$("#div").index($this)在setTimeoutt中返回值一直是-1的问题解决方案

今天遇到一个十分蛋疼的问题,花了我一个多小时才解决,其实十分简单,但我是新手,好了,事情是这样的:

我想让鼠标停留在某个元素一定时间再显示它隐藏的内容(不然你鼠标快速滑上滑下,反反复复,如果碰上slideDown(),会让电脑反应不过来的),刚开始代码如下:

var tid = 0;
        $( ".header_middle ul li" ).hover( function() {
            
            tid = setTimeout( function() {
                    $(".hm_con_1 ").slideDown(250);
                    var $t=$(this);
                    var $t_index=$t.index();
                    $(".hm_con_1 ul ").hide().eq($t_index).show();

            }, 100 );
        }, function() {
            clearTimeout( tid );//当在1秒内退出了hover事件就取消计时代码
        } );
            $(".content1").mouseover(function () {
                $(".hm_con_1").slideUp(250);
            })
        $(".header,.menu,.top").mouseover(function (e) {
            if ($(e.target).closest(".header_middle ul li").length === 0) {
                $(".hm_con_1").slideUp(250);
            }
        })
View Code

但结果是this一直获取不到鼠标hover的元素的值,$t_index返回的都是-1,最后才反现

原生态函数中使用jQuery中的 $(this)无效(好吧,我也不知道什么是原生态函数),

所以,

只能把var $t=$(this);拿到外面去定义了

 

var tid = 0;
        $( ".header_middle ul li" ).hover( function() {
            var $t=$(this);
            tid = setTimeout( function() {
                    $(".hm_con_1 ").slideDown(250);
                    var $t_index=$t.index();
                    $(".hm_con_1 ul ").hide().eq($t_index).show();

            }, 100 );
        }, function() {
            clearTimeout( tid );//当在1秒内退出了hover事件就取消计时代码
        } );
            $(".content1").mouseover(function () {
                $(".hm_con_1").slideUp(250);
            })
        $(".header,.menu,.top").mouseover(function (e) {
            if ($(e.target).closest(".header_middle ul li").length === 0) {
                $(".hm_con_1").slideUp(250);
            }
        })

 

posted @ 2018-02-03 22:33  兰亭序乱  阅读(670)  评论(0编辑  收藏  举报