如何在 jQuery 'on' 对象中创建方法之间共享的变量?



我试图在悬停和用户离开(并可能在窗口内单击(悬停元素时都有一些逻辑:

jQuery('.element').on({
    mouseenter: function() {
    },
    mouseleave: function() {
    }
});

问题是,对于每个方法,mouseentermouseleave,我必须重新初始化我感兴趣的公共变量,例如jQuery(this)引用我正在使用的当前元素。

我知道它们都是不同的事件,但是可以使用操纵的共同点在哪里,这样我就不必复制逻辑/重新初始化变量?

我想做类似的事情(我知道这不是正确的语法,但我需要某种构造函数(:

jQuery('.element').on(
    let shared_variable = jQuery(this), {
    mouseenter: function() {
    },
    mouseleave: function() {
    }
});

一种选择是只有一个手,绑定到多个事件,然后在处理程序中定义公共变量,检查哪个事件触发了它,并调用相应的其他函数:

const handlers = {
  mouseenter($this, shared) {
    $this.css('background-color', shared);
  },
  mouseleave($this, shared) {
    $this.css('background-color', '');
  }
}
jQuery('.element').on('mouseenter mouseleave', function(e) {
  const $this = jQuery(this);
  const shared = 'yellow';
  handlers[e.type]($this, shared);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">hover</div>

您还可以在处理程序中定义对象以避免传递变量,但即使它需要较少的代码,它也有点不优雅:

jQuery('.element').on('mouseenter mouseleave', function(e) {
  const handlers = {
    mouseenter() {
      $this.css('background-color', shared);
    },
    mouseleave() {
      $this.css('background-color', '');
    }
  };
  const $this = jQuery(this);
  const shared = 'yellow';
  handlers[e.type]();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">hover</div>

如果有许多这样的公共变量,则可以考虑改用包含这些公共变量的对象:

const handlers = {
  mouseenter({ $this, shared1 }) {
    $this.css('background-color', shared1);
  },
  mouseleave({ $this, shared2 }) {
    $this.css('background-color', shared2);
  }
}
jQuery('.element').on('mouseenter mouseleave', function(e) {
  const shared = 'yellow';
  const sharedParams = {
    $this: jQuery(this),
    shared1: 'yellow',
    shared2: 'orange'
  };
  handlers[e.type](sharedParams);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">hover</div>

为什么不使用 .on(( 数据参数?

var yourObject = {color: 1};
$('.element').on('mouseenter', yourObject, function(e) {
    var x = e.data.color;
    console.log(e.type + ' --> ' + x);
    e.data.color += 1;
});
$('.element').on('mouseleave',  yourObject, function(e) {
    var x = e.data.color;
    console.log(e.type + ' --> ' + x);
    e.data.color += 1;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">hover</div>

最新更新