简体   繁体   English

将事件处理程序附加到DOM元素

[英]Attaching event handler to DOM elements

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 from my .js file instead of directly calling it from an HTML attribute. 我唯一想知道的是,是否可以从我的.js文件中为onclick添加事件处理程序,而不是直接从HTML属性中调用它。 Here is the bit of HTML that uses the onclick : 以下是使用onclick的HTML:

<div id="left">
        <div id="board">
            <div id="one" onclick="playerMove(this)">

            </div>
            <div id="two" onclick="playerMove(this)">

            </div>
            <div id="three" onclick="playerMove(this)">

            </div>
            <div id="four" onclick="playerMove(this)">

            </div>
            <div id="five" onclick="playerMove(this)">

            </div>
            <div id="six" onclick="playerMove(this)">

            </div>
            <div id="seven" onclick="playerMove(this)">

            </div>
            <div id="eight" onclick="playerMove(this)">

            </div>
            <div id="nine" onclick="playerMove(this)">

            </div>
        </div>
    </div>

Any thoughts on the matter would be greatly appreciated. 任何对此事的想法将不胜感激。

If you use jQuery something like this should work: 如果您使用jQuery,则应该可以执行以下操作:

$(document).ready(function() {
  $('#board div').click(playerMove);
});

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). 在普通javascript(无跨平台库)中,可以使用addEventListener (现代浏览器)或attachEvent (IE的较旧版本)通过javascript代码添加事件处理程序。

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): 用法示例(在页面DOM加载后调用):

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

Or, to install event handlers for all the board divs, you could do this: 或者,要为所有主板div安装事件处理程序,可以执行以下操作:

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

You should really consider using jQuery for this. 您应该真正考虑为此使用jQuery。 If you were using jQuery, this would have been as simple as: 如果您使用的是jQuery,这将非常简单:

$('#board > div').click(playerMove);

In case you want to stick with vanilla JS, you can do: 如果您想使用香草JS,可以执行以下操作:

var items = document.getElementById('board').children;
for(x in items) {
    items[x].onclick = function() {
        playerMove(items[x]);
    };
}

Try: 尝试:

document.getElementById('one').onclick();

For binding the event handler in js file: 在js文件中绑定事件处理程序:

var board = document.getElementById('board'),
      divs = board.getElementsByTagName('div'),
      i, len = divs.length;
for (i = 0; i < len; i++) {
      divs[i].onclick = function() {
           playerMove(this); 
      };
}

Use this: 用这个:

document.getElementById('element_id').onclick = function(){ playerMove(this); };

For each Div, change 'element_id' with 'one', 'two', ... 对于每个Div,将“ element_id”更改为“一个”,“两个”,...

Your answer is in following 5 lines. 您的答案在以下5行中。 Try it :) If someone copies/converts my code in new post or my post to j-query, That is welcome with no problem. 尝试一下:)如果有人将我在新帖子中的代码/我的代码复制/转换为j-query,那是没有问题的。

var yourDivID = document.getElementById('your_Div_ID');
yourDivID.addEventListener('click', function (){  playerMove(this); }, false);
function playerMove(divElement)
{
    alert(divElement.id);
}

I have tried to put complete demo Here on jsfiddle.net , You can click any div out of nine to check its event if link does not work, then you can check the following code (working for me WIN7 and FireFox) 我试图将完整的演示放在jsfiddle.net上您可以在9个div中单击任意一个div以检查其事件(如果链接不起作用),然后可以检查以下代码(对我而言适用于WIN7和FireFox)

<html>
<head>
<title> Add Events Dynamically </title>
<script type="text/javascript">
    function add_DivClick_Events() {
        var nodes = document.getElementById('board').childNodes;
        for (var i = 0; i < nodes.length; i++) {
            if (i % 2 == 1) {
                nodes[i].addEventListener('click', function () {
                    playerMove(this);
                }, false);
            }
        }    
    }
    function playerMove(divElement)
    {
        alert(divElement.id);
    }  
    </script>
    <style type="text/css">
    #board div
    {
        width:20px;
        height:20px;
        border:2px solid;        
    }
    </style>
</head>
     <body onload='add_DivClick_Events()'>   
        <div id="left">
        <div id="board">
            <div id="one">

            </div>
            <div id="two">

            </div>
            <div id="three">

            </div>
            <div id="four">

            </div>
            <div id="five">

            </div>
            <div id="six">

            </div>
            <div id="seven">

            </div>
            <div id="eight">

            </div>
            <div id="nine">

            </div>
        </div>
    </div>
    </body>    
 </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM