05 - 事件

05.01 - 事件概述

一般的直接被执行的js代码,在浏览器加载完成的时候,再浏览器重新加载之前不会再次执行(除开用定时器延迟执行的代码),那么就意味着异步的代码执行操作需要通过其它的方式触发,那么触发的时机,通常是用户做了某些操作之后进行的,像这种用户的操作被称之为“事件”

常用事件列表

  • 鼠标事件
    • 单击:click
    • 双击:dblclick
    • 移入:mouseover、mouseenter
    • 移出:mouseout、mouseleave
    • 按下:mousedown
    • 抬起:mouseup
    • 移动:mousemove
    • 备注
      • 事件在使用属性赋值的方式进行绑定的时候,需要添加 on 在事件名前面
      • mouseover / mouseout 与 mouseenter / mouseleave 的区别在于,前者在其子级上同样会触发事件(冒泡),而后者不会
  • 窗口事件
    • 浏览器窗口大小改变:resize
    • 窗口滚动:scroll
  • 键盘事件
  • 文档事件
  • 表单事件

事件的定义方法(事件绑定)

  • 事件的触发实际上是执行了一个函数

  • 事件触发的对象可以是,dom节点,window,document, HttpRequest,等对象

  • 绑定事件实例:元素被点击时候执行弹窗

    • 匿名函数
    // 给document绑定一个点击事件
    document.  = function(){
      	alert(\"hello world!\");
    }
    • 命名函数
    // 给document绑定一个点击事件 fn 不需要括号
    document.  = fn;
    // 定义需要被绑定的事件
    function fn(){
      	alert(\"hello world!\");
    }
    • 标签属性
    <!-- 通过标签属性绑定 -->
    <div id=\"box\"  =\"fn()\"></div>
    
    < >
      function fn(){
          alert(\"hello world!\");
      }
    </ >

事件解绑

  • 事件重新赋值为null
<div id=\"box\"></div>

< >
  var dBox = document.getElementById(\"box\");
  // 绑定
  dBox.  = fn;
  // 解绑
  dBox.  = null;

  function fn(){
      alert(\"hello world!\");
  }
</ >
  • 重新绑定新的事件
<div id=\"box\"></div>

< >
  var dBox = document.getElementById(\"box\");
  // 绑定
  dBox.  = fn;
  // 再次绑定新的事件
  dBox.  = fn_new;

  function fn(){
      alert(\"fn\");
  }
  function fn_new(){
      alert(\"fn_new\");
  }
</ >

05.02 - this

this 是一个关键字,代表当前方法调用的时候所属的对象,也就是说只有当方法被调用的时候 this 的指向才能明确

this 的指向

  • 括号直接调用时 this 指向 window 对象
function fn(){
  console.log(\"我属于:\" + this);
}
// 方法名直接括号调用
fn(); // \"我属于:[  Window]\"

// 在子级作用域中调用直接括号调用
(function(){
  fn();// \"我属于:[  Window]\"
}());
  • 方法调用时 this 指向 触发事件的对象
<div id=\"box\">点我点我!</div>
< >
  var dBox = document.getElementById(\"box\");
  function fn(){
    console.log(\"我属于:\" + this);
  }

  // document 调用
  document.  = fn; // \"我属于:[  HTMLDocument]\"

  // 标签元素调用
  dBox.  = fn; // \"我属于:[  HTMLDivElement]\"
</ >

this 的使用场景

  • 点击修改,获取元素自身的属性
<div>点我点我!</div>
<div>点我点我!</div>
<div>点我点我!</div>
< >
  var dDiv = document.getElementsByTagName(\"div\");
  function setColor(){
    this.style.color = \"red\";
  }
  function getHTML(){
  	console.log( this.innerHTML );
  }
  for(var i=0;i<dDiv.length;i++){
    dDiv[i].  = setColor;
    dDiv[i].  = getHTML;
  }
</ >
  • 获取存储的自定义属性数据
<div>点我点我!</div>
<div>点我点我!</div>
<div>点我点我!</div>
< >
  var dDiv = document.getElementsByTagName(\"div\");
  for(var i=0;i<dDiv.length;i++){
    dDiv[i].index = i;
    dDiv[i].  = function(){
      alert(this.index);
    };
  }
</ >
收藏 打印