http://jsfiddle.net/yZSEA/懸停不與鼠標離開工作
$("p").hover(function() {
var $this = $(this).find('span');
$this.show();
}, function() {
$this.hide();
});
我不希望使用的mouseenter和鼠標離開,以避免醜陋的代碼,這個想法上面jQuery的文檔中給出,在邏輯上是好的,但在鼠標離開的部分沒不工作
http://jsfiddle.net/yZSEA/懸停不與鼠標離開工作
$("p").hover(function() {
var $this = $(this).find('span');
$this.show();
}, function() {
$this.hide();
});
我不希望使用的mouseenter和鼠標離開,以避免醜陋的代碼,這個想法上面jQuery的文檔中給出,在邏輯上是好的,但在鼠標離開的部分沒不工作
你的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();
});
這是否適合使用相同的變量名? –
第二個函數可以訪問var $ this嗎? –
'$ this'是每個函數的局部。這意味着第二個函數不能訪問它。您實際上並不需要在您的示例中聲明一個變量,但是,您可以簡單地調用'$(this).find('span')。show()'和$(this).find('span' ).hide()'。 –
這是因爲在mouseleave處理程序的上下文中,$this
是undefined
,您還應該在該處理程序中定義該變量。
您還可以使用on
和toggle
方法(如果它不醜):
$("p").on('mouseenter mouseleave', function(e) {
$('span', this).toggle(e.type === 'mouseenter');
});
$this
沒有在您的鼠標移開範圍內聲明。只需再次做.find
呼叫你的鼠標進行處理:
$("p").hover(function(){
$(this).find('span').show();
}, function(){
$(this).find('span').hide();
}
);
再次添加var $this = $(this).find('span');
當鼠標離開發生
$("p").hover(function(){
var $this = $(this).find('span');
$this.show();
}, function(){
var $this = $(this).find('span');
$this.hide();
});
$("p").hover(function(){
var $this = $(this).find('span');
$this.show();
}, function(){
var $this = $(this).find('span');
$this.hide();
}
);
加$給你的離開功能也:
$("p").hover(function(){
var $this = $(this).find('span');
$this.show();
}, function(){
var $this = $(this).find('span');
$this.hide();
}
);
$('p').hover(function() {
$(this).find('span').show();
},function() {
$(this).find('span').hide();
});
'$ this'沒有在第二個功能設置 - 嘗試'$(本).hide()' – SmokeyPHP
這是因爲在''mouseleave' $ this'不組。 – putvande