更新
在评论中,你说
我需要 id 其他元素,现在鼠标悬停在上面
那是一个不同的问题。为此,您需要知道鼠标已离开div
,并知道它已输入其他内容。我可能会为此使用mouseleave
and的组合mouseover
,如下所示:
$("#div_1").mouseleave(function() {
// We're leaving the div, set up to capture mouseover
$("....selector for a container of these elements...").one("mouseover", function(e) {
// Get the ID of the bottommost element
console.log(e.target.id);
// Or alternately, in case it doesn't have one
var elementWithID = $(e.target).closest('[id]');
if (elementWithID[0]) {
console.log(elementWithID[0].id);
}
});
});
但我会非常非常努力地想出一种不同的方式来满足基本需求。
原答案:
简短版本:
$("#div_1").mouseout(function() {
alert(this.id); // But I'd avoid alert if I were you, perhaps console.log?
});
但是请继续阅读...
长版:
当您使用 jQuery 设置事件处理程序时,调用该处理程序时,this
是对您挂钩事件的 DOM 元素的引用,当然id
也是属性的反射id
属性。
但是请记住mouseout
气泡mouseout
,因此只要鼠标离开您(其任何后代)中的元素div
,即使它没有离开div
本身,您也会收到该事件。如果您只想知道它何时离开div
但不离开其任何后代元素,请mouseleave
改用(最初仅限 IE,但 jQuery 提供跨浏览器)。
如果您想将其概括为所有具有 class 的 div foo
:
$("div.foo").mouseout(function() { // Or, of course, mouseleav
console.log(this.id);
});