jQuery 事件冒泡:获取原始元素鼠标悬停(用于表行突出显示)

发布于 2024-08-05 17:12:45 字数 786 浏览 10 评论 0 原文

我正在尝试减少表中的“onmouseover”事件侦听器(其中我突出显示悬停时的行)。我想通过将事件侦听器附加到整个表而不是每个 来实现此目的。 (我现在就是这样)。原因是 IE 反应非常慢,我发现的唯一答案是减少事件侦听器的数量。

示例代码:

<table id="myTable">
   <tr>
     <td>Somedata</td>
   </tr>
   <tr>
     <td>Somedata 2</td>
   </tr>
   <tr>
     <td>Somedata 3</td>
   </tr>       
</table>

在这种情况下,如果我将鼠标悬停在第二个 上,我就会明白“onmouseover”事件从 tr 冒泡到表。

我如何在 jQuery $('#myTable').mouseover 事件中找到哪个 tr 悬停并更改其 css 类?

编辑:这个想法来自这个SO问题(但不幸的是答案中没有源代码):加速 IE 中的多个 OnMouseOver 事件

I'm trying to reduce my 'onmouseover' event listeners in my table (in which I highlight rows on hover). I want to do this by attaching an event listener to the entire table instead of each <tr> (that's how I have it now). The reason is that IE is reacting very slow and the only answer I found to this was to reduce the number of event listeners.

Sample code:

<table id="myTable">
   <tr>
     <td>Somedata</td>
   </tr>
   <tr>
     <td>Somedata 2</td>
   </tr>
   <tr>
     <td>Somedata 3</td>
   </tr>       
</table>

In this scenario, if I hover over the second <tr>, I understand that the "onmouseover" event bubbles from tr to the table.

How could I find out in my jQuery $('#myTable').mouseover event which tr was hovered and change its css class?

Edit: The idea for this comes from this SO question (but unfortunately no source code in the answer): Speeding Up Multiple OnMouseOver Events in IE

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

潜移默化 2024-08-12 17:12:45

它称为事件委托

您使用的是 jQuery,这使得通过 元素变得微不足道="noreferrer">closest

$('#myTable').mouseover(function(event) {
    var tr = $(event.target).closest('tr');
    // do something with the <tr> element...
})

closest实际上是为了支持这样的事件委托而编写的。这是 live() 在内部使用的内容。

It's called event delegation.

You're using jQuery which makes it trivial to find the triggering <tr> element of the event, via closest:

$('#myTable').mouseover(function(event) {
    var tr = $(event.target).closest('tr');
    // do something with the <tr> element...
})

closest was in fact written to support event delegation like this. It's what live() uses internally.

谜兔 2024-08-12 17:12:45

您可以将鼠标悬停事件附加到表格,但每次您将鼠标悬停在表格的任何子元素上时,该函数都会触发。

$('#myTable').mouseover(function(e) {
  $(e.target).parents('tr');
});

这将为您提供悬停元素的 tr。

You can attach the mouseover event to the table but every time you mouseover any child element of the table that function will fire.

$('#myTable').mouseover(function(e) {
  $(e.target).parents('tr');
});

That will get you the tr of element that was hovered.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文