2

http://jsfiddle.net/yZSEA/

$("p").hover(function() {
    var $this = $(this).find('span');
    $this.show();
}, function() {
    $this.hide();
});

我不想使用mouseenter和mouseleave来避免丑陋的代码,上面的想法在jquery文档中给出,逻辑上很好但是mouseleave部分不起作用

4

7 回答 7

3

您尚未$this在 mouseleave 函数中定义,并且您的代码正在抛出:

未捕获的 ReferenceError: $this 未定义

var $this只需在 mouseleave 函数中重复您的声明:

$("p").hover(function(){
    var $this = $(this).find('span');
    $this.show();
}, function(){
    var $this = $(this).find('span');
    $this.hide();
});

工作 JSFiddle 演示

于 2013-10-11T11:29:55.570 回答
2

这是因为$this在 mouseleave 处理程序的上下文中undefined,您还应该在该处理程序中定义变量。

您还可以使用ontoggle方法(如果它不丑):

$("p").on('mouseenter mouseleave', function(e) {
    $('span', this).toggle(e.type === 'mouseenter');
});
于 2013-10-11T11:28:46.253 回答
0

$this未在您的 mouseout 范围内声明。只需.find在鼠标移出处理程序中再次调用:

$("p").hover(function(){
    $(this).find('span').show();
        }, function(){
            $(this).find('span').hide();
    }
);
于 2013-10-11T11:28:58.473 回答
0

var $this = $(this).find('span');当 mouseleave 发生时再次添加

$("p").hover(function(){
var $this = $(this).find('span');
$this.show();
    }, function(){
        var $this = $(this).find('span');
        $this.hide();
});
于 2013-10-11T11:28:58.513 回答
0
$("p").hover(function(){
    var $this = $(this).find('span');
    $this.show();
        }, function(){
            var $this = $(this).find('span');
    $this.hide();
    }
);
于 2013-10-11T11:29:02.203 回答
0

也将 $this 添加到您的离开函数中:

$("p").hover(function(){
        var $this = $(this).find('span');
        $this.show();
    }, function(){
           var $this = $(this).find('span');
           $this.hide();
    }
);
于 2013-10-11T11:29:04.317 回答
0
 $('p').hover(function() {
       $(this).find('span').show();

             },function() {

    $(this).find('span').hide();
   });

演示

于 2013-10-11T11:48:50.103 回答