首页 > 建站教程 > JS、jQ、TS >  用纯JavaScript替代jQuery之事件篇正文

用纯JavaScript替代jQuery之事件篇

        接上篇:用纯JavaScript替代jQuery之元素操作篇

>>>>Off

jQuery
$(el).off(eventName, eventHandler);

谷歌浏览器,火狐浏览器,IE8+
function removeEventListener(el, eventName, handler) {
  if (el.removeEventListener)
    el.removeEventListener(eventName, handler);
  else
    el.detachEvent('on' + eventName, handler);
}

removeEventListener(el, eventName, handler);

谷歌浏览器,火狐浏览器,IE9+
el.removeEventListener(eventName, eventHandler);

>>>>On

jQuery
$(el).on(eventName, eventHandler);

谷歌浏览器,火狐浏览器,IE8+
function addEventListener(el, eventName, handler) {
  if (el.addEventListener) {
    el.addEventListener(eventName, handler);
  } else {
    el.attachEvent('on' + eventName, function(){
      handler.call(el);
    });
  }
}

addEventListener(el, eventName, handler);

谷歌浏览器,火狐浏览器,IE9+
el.addEventListener(eventName, eventHandler);

>>>>Ready

jQuery
$(document).ready(function(){
});

谷歌浏览器,火狐浏览器,IE8+
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading')
        fn();
    });
  }
}

谷歌浏览器,火狐浏览器,IE9+
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

>>>>指定事件触发

jQuery
$(el).trigger('my-event', {some: 'data'});

谷歌浏览器,火狐浏览器,IE8+
// 自定义事件本身不支持,所以你要定义一个随机事件。只能用 jQuery 了╮(╯﹏╰)╭

谷歌浏览器,火狐浏览器,IE9+
if (window.CustomEvent) {
  var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('my-event', true, true, {some: 'data'});
}

el.dispatchEvent(event);

>>>>Trigger Native

jQuery
$(el).trigger('change');

谷歌浏览器,火狐浏览器,IE8+
if (document.createEvent) {
  var event = document.createEvent('HTMLEvents');
  event.initEvent('change', true, false);
  el.dispatchEvent(event);
} else {
  el.fireEvent('onchange');
}

谷歌浏览器,火狐浏览器,IE9+
//对于一个事件类型的完整列表可以参见: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);