【问题标题】:Why callback function after not($(this)) repeats multiple times?为什么 not($(this)) 之后的回调函数重复多次?
【发布时间】:2013-09-09 04:34:41
【问题描述】:

我已经做了一个回调函数,打算在之后触发

$('.menuIco').not($(this)).fadeOut()

但我有 9 个回调而不是 1 个回调(可能是因为 not($(this)) 导致 10-1=9 个元素)。

为什么?以及如何预防?

我正在使用带有变量的解决方法,但在我看来它并不专业。

var loaded = false;

$('.menuIco').not($(this)).fadeOut(function() { // hide all icons but one
    if(loaded==false) {
        loaded = true;

        $('.menuIco p').addClass("icoCaptionOff");
        $(menuIco).animate({top: "20", left: "-100"}, "fast", function() {
            LoadContent($(menuIco).attr('id'));

        });
    }
});

【问题讨论】:

  • 请您也发布一些 HTML 代码。塔
  • 你必须包含封装的javascript,这样我们才能看到$(this)指的是什么
  • 您也可以只使用.not(this) 而不是.not($(this))
  • 什么叫9次?下面的匿名函数fadeOut() 或LoadContent()?
  • 仅供参考,.not(this) 就足够了。无需将其包装在 jquery 元素中。

标签: javascript jquery callback this


【解决方案1】:

您可能希望在 $(this) 上应用回调,而不是在每个回调函数中的每个 .menuIco 上应用。

$('.menuIco').not(this).fadeOut(function() { // hide all icons but one

        $(this).find('p').addClass("icoCaptionOff");

        $(this).animate({top: "20", left: "-100"}, "fast", function() {
            LoadContent($(this).attr('id'));
        });

});

【讨论】:

    【解决方案2】:

    您可以使用when 和then 延迟处理程序在另一个功能完成时执行:

    提供一种基于一个或多个执行回调函数的方法 对象,通常是表示异步事件的延迟对象。

    文档:http://api.jquery.com/jQuery.when/

    代码:

    $('.menuIco').click(function () {
        $.when($('.menuIco').not(this).fadeOut()).then(function () {
            console.log('foo')
        })
    })
    

    演示:http://jsfiddle.net/IrvinDominin/hvm79/

    【讨论】:

      【解决方案3】:

      你可以使用.promise()在所有元素的动画完成后执行回调

      .promise() 方法返回一个动态生成的 Promise,它是 一旦某种类型的所有动作都绑定到集合,就解决了, 排队与否,已经结束。

      type默认为“fx”,表示返回的Promise被解析 当所选元素的所有动画都完成时。

      $('.menuIco').not(this).fadeOut().promise().done(function () {
          $('.menuIco p').addClass("icoCaptionOff");
          $(menuIco).animate({
              top: "20",
              left: "-100"
          }, "fast", function () {
              LoadContent($(menuIco).attr('id'));
      
          });
      });
      

      【讨论】:

        【解决方案4】:

        您可能有多个类为.menuIco 的元素。所以在你的回调中你应该使用$(this)而不是再次选择$('.menuIco p')。

        var loaded = false;
        
        $('.menuIco').not($(this)).fadeOut(function() { // hide all icons but one
            var $this = $(this);
        
            if(loaded==false) {
                loaded = true;
        
                $this.find('p').addClass("icoCaptionOff");
                $this.animate({top: "20", left: "-100"}, "fast", function() {
                    LoadContent($this.attr('id'));
                });
            }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          • 2016-10-11
          相关资源
          最近更新 更多