帮助我理解JavaScript事件

Ani*_*mde 3 javascript

我有一个充满细胞的桌子,我想知道鼠标是哪个细胞.

为此,我已将事件附加到所有单元格,然后我找到了元素.但我想可能会有更好的选择.对 ?

是否有可能我只在顶部附加单个事件处理程序,仍然能够捕获所有信息.喜欢哪个细胞用户目前在等

像下面的东西,

<table onMouseOver="monitorFuntion(event)" >...</table>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

可以完全按照你所说的做:你可以在桌面上放置一个处理程序,然后从中找到单元格.(这有时被称为" 事件委托 ".)您可以为某些事件执行此操作,包括mouseovermouseout,因为它们会冒泡.你不能为其他事件(比如blurfocus)做这件事,因为它们不会冒泡.

假设您有一个ID为"myTable"的表.您可以为以下内容挂钩事件处理程序mouseover:

var table = document.getElementById("myTable");
if (table.attachEvent) {
    table.attachEvent("onmouseover", handleMouseOver);
}
else {
    table.addEventListener("mouseover", handleMouseOver);
}
Run Code Online (Sandbox Code Playgroud)

然后像这样处理它:

function handleMouseOver(event) {
    var target;

    // Handle IE event difference from standard
    event = event || window.event;

    // Find out what element the event actually happened on
    // (Another IE difference here, srcElement vs target)
    target = event.srcElement || event.target;

    // Since that might be an element *within* your cell (like
    // a link, or a `span`, or a `strong`, etc.), find the cell
    while (target && target.tagName != "TD" && target.tagName != 'BODY') {
        target = target.parentNode;
    }
    if (target && target.tagName != 'BODY') {
        // Found one, `target` now points to the cell the mouse is over
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,处理target结束null或引用body元素的情况非常重要,因为您将在表的边框,行填充等上获得此事件.

JavaScript库可以帮助你跟这个有很多.例如,上面使用Prototype看起来像这样:

$("myTable").observe("mouseover", handleMouseOver);

function handleMouseOver(event) {
    var target;

    target = event.findElement("td");
    if (target) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

jQuery,Closure和其他人同样会有所帮助.