$("p").hover(function() {
var $this = $(this).find('span');
$this.show();
}, function() {
$this.hide();
});
我不想使用mouseenter和mouseleave来避免丑陋的代码,上面的想法在jquery文档中给出,逻辑上很好但是mouseleave部分不起作用
$("p").hover(function() {
var $this = $(this).find('span');
$this.show();
}, function() {
$this.hide();
});
我不想使用mouseenter和mouseleave来避免丑陋的代码,上面的想法在jquery文档中给出,逻辑上很好但是mouseleave部分不起作用
您尚未$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();
});
这是因为$this
在 mouseleave 处理程序的上下文中undefined
,您还应该在该处理程序中定义变量。
您还可以使用on
和toggle
方法(如果它不丑):
$("p").on('mouseenter mouseleave', function(e) {
$('span', this).toggle(e.type === 'mouseenter');
});
$this
未在您的 mouseout 范围内声明。只需.find
在鼠标移出处理程序中再次调用:
$("p").hover(function(){
$(this).find('span').show();
}, function(){
$(this).find('span').hide();
}
);
var $this = $(this).find('span');
当 mouseleave 发生时再次添加
$("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();
}
);
也将 $this 添加到您的离开函数中:
$("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();
});