Attaching event handler to DOM elements

前端 未结 6 659
[愿得一人]
[愿得一人] 2021-01-28 12:30

I am working on a tic tac toe game, which is almost complete. The only thing I am left wondering about is if it is possible to add an event handler for onclick fro

6条回答
  •  遥遥无期
    2021-01-28 12:41

    In plain javascript (no cross platform libraries), event handlers can be added via javascript code with addEventListener (modern browsers) or attachEvent (older versions of IE).

    Here's a simple function that adds an event handler in a cross browser fashion:

    // add event cross browser
    function addEvent(elem, event, fn) {
        if (elem.addEventListener) {
            elem.addEventListener(event, fn, false);
        } else {
            elem.attachEvent("on" + event, function() {
                // set the this pointer same as addEventListener when fn is called
                return(fn.call(elem, window.event));   
            });
        }
    }
    

    Example usage (called after the page DOM has loaded):

    addEvent(document.getElementById("one"), 'click', playerMove);
    

    Or, to install event handlers for all the board divs, you could do this:

    var divs = document.getElementById("board").children;
    for (var i = 0, len = divs.length; i < len; i++) {
        // element nodes only
        if (divs[i].nodeType === 1) {
            addEvent(divs[i], 'click', playerMove);
        }
    }
    

提交回复
热议问题