$(this) 返回"未定义"



编辑:
似乎注册mouseenter的项目不正确。所以我想这个问题已经解决了。

在以下代码中

$(".nav").mouseenter(function(){
     $('.'+$(this).attr("id")).stop().animate({"opacity": 1}, 800);
});  

$(this)返回的是[object Object],而不是鼠标输入的项目
编辑:
在将confirm($(this));添加为.mousenter函数内的最后一行并将鼠标悬停在其中一个区域后,对话框显示[object Object]。id为的Things是查找类等于鼠标悬停对象id的元素。我在控制台中单独测试了这段代码,它运行得很好。在使用$(this)运行console.log之后,$(this以下是受影响的html:

<div id="body">
<span class="nav current" id="1">Home</span>
<span class="nav" id="2">Music</span>
<span class="nav" id="3">More</span>
</div>
<span class="nav background 1">Home</span>
<span class="nav background 2">Music</span>
<span class="nav background 3">More</span>

$(this)实际上是触发函数调用的对象。

正确代码:

$(".nav").mouseenter(function(){
     $(this).stop().animate({"opacity": 1}, 800);
});  

由于事件处理程序依赖于具有ID的元素,因此我会使初始选择器更加健壮。此外,不需要将this封装在jQuery对象中,所以我也会删除它。。。

// only find .nav elements that also have an "id" attribute
$('.nav[id]').on('mouseenter', function(e) {
    // here, `this` is the .nav element that has received a `mouseenter` event
    var selector = '.' + this.id;
    $(selector).stop().animate({ opacity: 1 }, 800);
});

最新更新