Help me understand JavaScript events

I have a table full of cells, and I would like to know which cell the mouse is on.

To do this, I attached events to all cells, and then I discovered elements. But I think there may be better options. right?

Is it possible that I attach only one event handler from above and can still catch all the information. for example, which cell user is currently enabled, etc.

Something like below

<table onMouseOver="monitorFuntion(event)" >...</table>
+3
source share
3 answers

, : , . ( " ".) , mouseover mouseout, . (, blur focus), .

, "myTable". mouseover:

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

:

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
    }
}

, , , target null body, , ..

Javascript . , Prototype :

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

function handleMouseOver(event) {
    var target;

    target = event.findElement("td");
    if (target) {
        // ...
    }
}

jQuery, Closure, .

+5

, , . IE , "" :

 function handler(ev) {
   ev = ev || window.event;
   var targetElement = ('target' in ev) ? ev.target : ev.srcElement;
   // ...
 }

"" , , . "". , jQuery Prototype, .

IE

+3

, , .

Step 1: use jQuery 1.4.2 +

Step 2:

// you can use move, enter, out, over whatever...
$("table").delegate("mouseenter", "td", click, function(){
    var tableCell = $(this); // the cell which is currently moused-over.
});
+3
source

Source: https://habr.com/ru/post/1742106/


All Articles