我正在尝试减少表中的“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
发布评论
评论(2)
它称为事件委托。
您使用的是 jQuery,这使得通过 元素变得微不足道="noreferrer">
closest
:closest
实际上是为了支持这样的事件委托而编写的。这是live()
在内部使用的内容。It's called event delegation.
You're using jQuery which makes it trivial to find the triggering
<tr>
element of the event, viaclosest
:closest
was in fact written to support event delegation like this. It's whatlive()
uses internally.您可以将鼠标悬停事件附加到表格,但每次您将鼠标悬停在表格的任何子元素上时,该函数都会触发。
这将为您提供悬停元素的 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.
That will get you the tr of element that was hovered.