无法获取未定义或空引用的属性'hasClass'

时间:2014-09-10 23:17:16

标签: jquery angularjs reference null undefined

我正在使用AngularJS框架,我在jquery中使用'hasClass'以便鼠标悬停下拉。它在chrome和FF中运行良好,但在IE中,当我点击按钮并导航到另一个页面时,它会出现“无法获取属性hasClass of undefined或null reference”的错误。 此错误不会每次都显示,但它经常出现在IE中。 类似地,有时代替'hasClass',它会将'height'抛出为undefined或null引用。 这是代码:

(function ($, window, delay) {

        var theTimer = 0;
        var theElement = null;
        var theLastPosition = { x: 0, y: 0 };
        $('[data-toggle]')
          .closest('li')
          .on('mouseenter', function (inEvent) {
              if (theElement) theElement.removeClass('open');
              window.clearTimeout(theTimer);
              theElement = $(this);

              theTimer = window.setTimeout(function () {
                  theElement.addClass('open');
              }, delay);
          })
          .on('mousemove', function (inEvent) {
              if (Math.abs(theLastPosition.x - inEvent.ScreenX) > 4 ||
                 Math.abs(theLastPosition.y - inEvent.ScreenY) > 4) {
                  theLastPosition.x = inEvent.ScreenX;
                  theLastPosition.y = inEvent.ScreenY;
                  return;
              }

              if (theElement.hasClass('open')) return;
              window.clearTimeout(theTimer);
              theTimer = window.setTimeout(function () {
                  theElement.addClass('open');
              }, delay);
          })
          .on('mouseleave', function (inEvent) {
              window.clearTimeout(theTimer);
              theElement = $(this);
              theTimer = window.setTimeout(function () {
                  theElement.removeClass('open');
              }, delay);
          });
    })(jQuery, window, 50); // 50 is the delay in milliseconds

有什么建议吗? 感谢。

1 个答案:

答案 0 :(得分:0)

可能的问题是,mousemove事件在某些情况下可能会比mouseenter更早发生。

然后,在theElement事件监听器中更好地检查null是否仍为mousemove

.on('mousemove', function (inEvent) {
    /* ... */
    if (!theElement || theElement.hasClass('open')) { return; }
    window.clearTimeout(theTimer);
    theTimer = window.setTimeout(function () {
        theElement.addClass('open');
    }, delay);
})