You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在鼠标悬停事件中测试元素ID值?解决this获取ID为undefined问题

解决鼠标悬停时获取元素ID为undefined的问题

问题根源

你遇到的undefined问题,核心是内联事件处理函数中this的上下文不对。当你直接写onmouseover="mouseOver()"时,函数里的this指向的是全局的window对象,而不是触发悬停的<td>元素,所以$(this).attr("ID")自然拿不到目标元素的ID值。另外还有个小细节:jQuery的attr()方法里,属性名建议用小写的"id"(虽然HTML属性大小写不敏感,但jQuery内部处理更规范)。


解决方案1:修改内联事件,传递当前元素

最简单的修改方式是在调用函数时把this传进去,这样函数就能直接拿到触发事件的元素:

修改后的HTML:

<table>
  <tr data-ng-repeat="x in Interruptions">
    <td id="row{{x.year}}" onmouseover="mouseOver(this)" onmouseout="mouseOut()">
      {{x.year}}
    </td>
    <td>{{x.totalEvents}}</td>
    <td>{{x.customers}}</td>
    <td>{{x.avgDuration}}</td>
  </tr>
</table>

修改后的JS函数:

function mouseOver(element) {
  var e = $(element).attr("id"); // 改用小写的id
  if (e === "row2012") {
    alert(e);
  } else {
    alert(e);
  }
}

解决方案2:使用jQuery事件绑定(更推荐)

既然你已经在用jQuery,更优雅的方式是去掉内联事件,用jQuery的事件绑定来处理,这样this会自动指向触发事件的元素:

HTML(移除内联事件):

<table>
  <tr data-ng-repeat="x in Interruptions">
    <td id="row{{x.year}}" class="hoverable"> <!-- 加个类用来定位元素 -->
      {{x.year}}
    </td>
    <td>{{x.totalEvents}}</td>
    <td>{{x.customers}}</td>
    <td>{{x.avgDuration}}</td>
  </tr>
</table>

JS代码:

$(document).ready(function() {
  // 给所有带hoverable类的td绑定鼠标悬停事件
  $(".hoverable").on("mouseover", function() {
    var e = $(this).attr("id");
    alert(e); // 这里可以按你的逻辑判断处理
  });
});

额外提示(针对Angular场景)

因为你用了AngularJS的ng-repeat,如果是动态生成的元素,上面的jQuery绑定可能会因为元素还没渲染完成而失效。这时候可以用Angular的ng-mouseover指令,更符合Angular的开发方式:

HTML:

<table>
  <tr data-ng-repeat="x in Interruptions">
    <td id="row{{x.year}}" ng-mouseover="mouseOver($event)">
      {{x.year}}
    </td>
    <td>{{x.totalEvents}}</td>
    <td>{{x.customers}}</td>
    <td>{{x.avgDuration}}</td>
  </tr>
</table>

在Angular控制器里定义函数:

$scope.mouseOver = function(event) {
  var e = event.target.id; // 直接通过事件对象获取元素ID
  if (e === "row2012") {
    alert(e);
  } else {
    alert(e);
  }
};

这样既符合Angular的数据流逻辑,也能稳稳获取到元素的ID啦~


内容的提问来源于stack exchange,提问作者Amaranth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:02:40