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

问题描述 投票:1回答:2

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

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

    }
});

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

我知道它们都是不同的事件,但是可以使用的共同点是什么 - 操作,所以我不必复制逻辑/重新初始化变量?

我正在寻找类似的东西(我知道它的语法不正确,但我需要一些构造函数):

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

    }
});
jquery
2个回答
2
投票

一个选项是只有一个hander,绑定到多个事件,然后在处理程序中定义公共变量,检查触发它的事件,并调用适当的其他函数:

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>

1
投票

为什么不使用.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>
© www.soinside.com 2019 - 2024. All rights reserved.