Home > Web Front-end > JS Tutorial > body text

Detailed explanation of examples of event handlers in JavaScript

黄舟
Release: 2017-09-22 10:15:41
Original
1153 people have browsed it

This article mainly introduces the relevant information of JavaScript event handlers in detail, which has certain reference value. Interested friends can refer to it

The examples in this article share with you js event processing The specific code of the program is for your reference. The specific content is as follows


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM0级DOM2级</title>
</head>
<body>
<input id="btn1" type="button" value="click1" onclick="show()">
<input id="btn2" type="button" value="click2">
<input id="btn3" type="button" value="click3">
<script>
  function show() {
    alert("btn1");
  }
  //DOM0级
  var btn2 = document.getElementById("btn2");
  btn2.onclick = function () {
    alert("DOM0级btn2");
  };
  //DOM2级
  function show2() {
    alert("DOM2级btn3");
  }
  var btn3 = document.getElementById("btn3");
//  btn3.addEventListener("click",show2,false);
//  btn3.removeEventListener("click",show2,false);
  //ie事件处理程序
//  btn3.attachEvent("onclick",show2);
//  btn3.detachEvent("onclick",show2);
  //跨浏览器事件处理程序
  //能力检测
var eventUtil = {
    //添加具柄;
    addHandler:function (element,type,handler) {
      if (element.addEventListener){
        element.addEventListener(type,handler,false);
      }else if(element.attachEvent){
        element.attachEvent("on"+type,handler);
      }else {
        element["on"+type]=handler;
      }
    },
    //删除具柄;
    removeHandler:function (element,type,handler) {
      if (element.removeEventListener){
        element.removeEventListener(type,handler,false);
      }else if(element.detachEvent){
        element.detachEvent("on"+type,handler);
      }else {
        element["on"+type]=null;
      }
    }
};
eventUtil.addHandler(btn3,"click",show2);
eventUtil.removeHandler(btn3,"click",show2);
</script>
</body>
</html>
Copy after login

The above is the detailed content of Detailed explanation of examples of event handlers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template