jQuery事件,获得$(this)的正确上下文

时间:2017-02-02 05:18:51

标签: jquery binding this bind delegation

我需要使用正确的$featuredImage上下文在mouseenter和mouseleave事件之外声明$(this),以避免代码重复。众所周知,mouseenter / mouseleave之外的$(this)是一个空对象。我想将$(this)绑定到正确的上下文,只分配$featuredImage一次并从两个函数中访问它,但我似乎找不到好的方法。

function postThumbOverlay() {

  var $featuredImage;

  $(document).on({
      mouseenter: function(e) {
          // duplicated
          $featuredImage = $(this).parents('.grid').children( '.entry__featured-image' );
          $featuredImage.find('.entry__featured-image--overlay').addClass( 'show--overlay' );
          e.stopPropagation();
      },
      mouseleave: function() {
          // duplicated
          $featuredImage = $(this).parents('.grid').children('.entry__featured-image');
          $featuredImage.find('.entry__featured-image--overlay').removeClass( 'show--overlay' );
      }
  }, '.entry-link');
}

我没有使用.on('hover')的原因是因为这样做会在AJAX调用后停止工作,我需要单独使用mouseentermouseleave

1 个答案:

答案 0 :(得分:0)

将其解压缩为方法 -

function getFeaturedImageElement($this){
 return $this.parents('.grid').children( '.entry__featured-image' );
}

并在事件中调用它 - var $featuredImage = getFeaturedImageElement($(this));

如果您真的想避免在每个事件上查询DOM,那么请检查该方法(将$featuredImage保持为全局) -

var $featuredImage;
function getFeaturedImageElement($this){
   if(!$featuredImage){ 
     $featuredImage = $this.parents('.grid').children( '.entry__featured-image'); 
    } 
   return $featuredImage;
}