未捕获的TypeError:无法在'EventTarget'上执行'addEventListener':作为参数2提供的回调不是对象

时间:2018-11-02 16:50:48

标签: javascript jquery vanilla-typescript

在克里斯·费迪南迪(ChrisFerdinandi)的"Go Make Great Things" blog上,有一篇很棒的文章介绍了如何从jQuery库中创建.on()方法的“ Vanilla JS”版本。

var on = function (event, elem, callback, capture) {
    if (typeof (elem) === 'function') {
        capture = callback;
        callback = elem;
        elem = window;
    }
    capture = capture ? true : false;
    elem = typeof elem === 'string' ? document.querySelector(elem) : elem;
    if (!elem) return;
    elem.addEventListener(event, callback, capture);
}; 

我是否因为需要addEventListener使用字符串来设置冒泡或捕获而需要三元或某些条件吗?

capture = capture ? true : false;
capture = capture  === true ? 'true' : 'false';

所以我试图利用上面的代码来创建过渡,但是我得到了,

Uncaught TypeError: Failed to execute 'addEventListener' on 'EventTarget': The callback provided as parameter 2 is not an object.

这是标记:

     <a href = "#">
       <img class="make-up-img color-palette" alt="Eyes on you - Color Palette"
src="https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink$" />
    </a>

这是脚本:

var on = function(event, elem, callback, capture) {
  if (typeof elem === 'function') {
    capture  = callback;
    callback = elem;
    elem     = window;
  }
    console.log(capture)

  capture = capture ? true : false;
  capture = capture  === true ? 'true' : 'false';

  console.log(capture)

  elem = typeof elem === 'string' ? document.querySelector(elem) : elem;
  if (!elem) return;
  elem.addEventListener(event, callback, capture);
};



function rollOver(elem){
  if (document.querySelector(elem).getAttribute('src', 'https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink')) {
  return document.querySelector(elem).getAttribute('src', 'https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink')
  }
   return document.querySelector(elem).getAttribute('src', 'https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/EYES_ON_YOU_desktop_HP_NO_HOVER_1.jpg?$staticlink');
}


on('mouseover', '.color-palette', rollOver('.color-palette'));

0 个答案:

没有答案