2013-10-11 131 views
2

http://jsfiddle.net/yZSEA/懸停不與鼠標離開工作

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

我不希望使用的mouseenter和鼠標離開,以避免醜陋的代碼,這個想法上面jQuery的文檔中給出,在邏輯上是好的,但在鼠標離開的部分沒不工作

+0

'$ this'沒有在第二個功能設置 - 嘗試'$(本).hide()' – SmokeyPHP

+0

這是因爲在''mouseleave' $ this'不組。 – putvande

回答

3

你的mouseleave函數中沒有定義$this,你的代碼是拋出荷蘭國際集團:

Uncaught ReferenceError: $this is not defined

簡單重複的鼠標離開功能您var $this聲明:

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

Working JSFiddle demo

+0

這是否適合使用相同的變量名? –

+0

第二個函數可以訪問var $ this嗎? –

+0

'$ this'是每個函數的局部。這意味着第二個函數不能訪問它。您實際上並不需要在您的示例中聲明一個變量,但是,您可以簡單地調用'$(this).find('span')。show()'和$(this).find('span' ).hide()'。 –

2

這是因爲在mouseleave處理程序的上下文中,$thisundefined,您還應該在該處理程序中定義該變量。

您還可以使用ontoggle方法(如果它不醜):

$("p").on('mouseenter mouseleave', function(e) { 
    $('span', this).toggle(e.type === 'mouseenter'); 
}); 
0

$this沒有在您的鼠標移開範圍內聲明。只需再次做.find呼叫你的鼠標進行處理:

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

再次添加var $this = $(this).find('span');當鼠標離開發生

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

加$給你的離開功能也:

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

      },function() { 

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

Demo