简单的监听事件

添加一个简单的监听器

下面这个例子用来展示如何使用 addEventListener() 监听鼠标点击一个元素。

<table id="outside">    
    <tr><td id="tt">one</td></tr>
    <tr><td id="th">two</td></tr>
</table>
// 改变t2的函数
function modifyText() {
  var th= document.getElementById("th");
  if (th.firstChild.nodeValue == "three") {
    th.firstChild.nodeValue = "two";
  } else {
    th.firstChild.nodeValue = "three";
  }
}

// 为table添加事件监听器
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);

在上个例子中,modifyText() 是一个 click 事件的监听器,通过使用addEventListenter()注册到table对象上。在表格中任何位置单击都会触发事件并执行modifyText()

posted on 2019-05-15 15:41  梦回太古  阅读(150)  评论(0编辑  收藏  举报

导航