【问题标题】:What to use instead of `toggle(...)` in jQuery > 1.8?在 jQuery > 1.8 中使用什么来代替 `toggle(...)`?
【发布时间】:2013-01-17 15:50:32
【问题描述】:

现在toggle(...)deprecated in jQuery 1.8,然后是removed in jQuery 1.9

general 中可以使用什么(除了使用 jQuery 迁移脚本)而不是 toggle(fn, fn2); 具有相同类型的功能?

相关问题(询问具体案例):What to use instead toggle?


知道 toggle() 功能没有被删除,只是添加自定义切换功能的能力(除了显示/隐藏默认功能)。

【问题讨论】:

  • slideToggle 还有效吗?
  • @Lokase 我不明白为什么不会?
  • 如果您经常使用它,只需自己实现它,这里有几个例子:forum.jquery.com/topic/… 我发现如果它隐藏在函数后面而不是到处都有计数器变量,更容易理解。
  • 这是一种用途广泛的方法,但命名不便。该方法被广泛使用并且确实节省了代码,但是 .toggle() show hide 使用得更多,因此删除了前者以简化 api。
  • @Lokase:切换事件 (api.jquery.com/toggle-event) 已被弃用;切换效果 (api.jquery.com/toggle) 已被弃用。模棱两可是事件发生/消失的部分原因 (bugs.jquery.com/ticket/11786#comment:1)

标签: toggle jquery


【解决方案1】:

这是一个简单的实现:

$.fn.toggleClick = function() {
    var methods = arguments;    // Store the passed arguments for future reference
    var count = methods.length; // Cache the number of methods 

    // Use return this to maintain jQuery chainability
    // For each element you bind to
    return this.each(function(i, item){
        // Create a local counter for that element
        var index = 0;

        // Bind a click handler to that element
        $(item).on('click', function() {
            // That when called will apply the 'index'th method to that element
            // the index % count means that we constrain our iterator between 0
            // and (count-1)
            return methods[index++ % count].apply(this, arguments);
        });
    });
};

并将其用作

$('selector').toggleClick( function1, function2, ... );

【讨论】:

  • 喜欢。您可以添加一些 cmets 向人们解释这一切吗? ^_^
  • @Neal,进行了更新,因为我忘记了 return this 来维护链接..
  • 为什么在点击处理程序中需要return
  • @Neal,以便我们尊重用户使用他们传递的方法所做的事情。例如,如果应用于链接,用户可能会在最后执行return false,我们希望将其传递给我们自己的点击处理程序以供使用。
  • 这是否像旧的 JQuery 切换一样工作?我想我的问题真的是,我可以使用这个功能的效果吗?像老一样:toggle('slow', function(){...})
猜你喜欢
  • 1970-01-01
  • 2013-01-07
  • 2014-08-25
  • 2013-09-17
  • 2020-05-15
  • 2011-10-02
  • 2011-10-12
  • 1970-01-01
  • 2018-11-24
相关资源
最近更新 更多