替代支持eventData的jQuery的.toggle()方法? [英] Alternative to jQuery's .toggle() method that supports eventData?

查看:163
本文介绍了替代支持eventData的jQuery的.toggle()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.toggle() jQuery文档 $ c>方法声明:

The jQuery documentation for the .toggle() method states:


为方便起见,提供了.toggle()方法。手动执行相同的行为是比较直接的,如果.toggle()中的假设证明是有限制的,这可能是必要的。

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting.

内置于 .toggle 中的假设已被证明是对我当前任务的限制,但是文档没有详细说明如何实现相同的行为。我需要将eventData传递给提供给 toggle()的处理函数,但似乎只有 .bind()将支持这一点,而不是 .toggle()

The assumptions built into .toggle have proven limiting for my current task, but the documentation doesn't elaborate on how to implement the same behavior. I need to pass eventData to the handler functions provided to toggle(), but it appears that only .bind() will support this, not .toggle().

我的第一个倾向是使用全局的标志单个处理函数存储点击状态。换句话说,而不是:

My first inclination is to use a flag that's global to a single handler function to store the click state. In other words, rather than:

$('a').toggle(function() {
  alert('odd number of clicks');
}, function() {
  alert('even number of clicks');
});

执行此操作:

var clicks = true;
$('a').click(function() {
  if (clicks) {
    alert('odd number of clicks');
    clicks = false;
  } else {
    alert('even number of clicks');
    clicks = true;
  }
});

我没有测试过后者,但我怀疑它会工作。这是做这样的事情的最好办法,还是有更好的方法,我失踪了?

I haven't tested the latter, but I suspect it would work. Is this the best way to do something like this, or is there a better way that I'm missing?

谢谢!

推荐答案

似乎是一个合理的方式来做...我只是建议你使用jQuery的数据存储实用程序,而不是引入一个额外的变量(如果你想跟踪一大堆链接可能会变得头痛)。所以根据你的例子:

Seems like a reasonable way to do it... I'd just suggest that you make use of jQuery's data storage utilities rather than introducing an extra variable (which could become a headache if you wanted to keep track of a whole bunch of links). So based of your example:

$('a').click(function() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    alert('odd number of clicks');
  } else {
    alert('even number of clicks');
  }
  $(this).data("clicks", !clicks);
});

这篇关于替代支持eventData的jQuery的.toggle()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆