【问题标题】:How to pass parameter to jQuery . animate option object complete property?如何将参数传递给 jQuery 。动画选项对象的完整属性?
【发布时间】:2012-09-13 07:46:35
【问题描述】:

我知道问题的标题令人困惑。这也让我很难找到解决方案。

假设我有这些代码,当 .animate() 选项是外部对象时,如何将参数传递给 completestep

var someObj = {
    onComplete: function(e) {
        console.log(e); // return undefined
    },

    onStep: function(e) {
        console.log(e); // return undefined too
    },
}

var optionObj = {
    duration: 300,
    easing: 'linear',
    complete: someObj.onComplete(e), // this is not working
    step: someObj.onStep(e) // this is not working
}

$('div').animate({width: "500px", height: "500px"}, optionObj);

【问题讨论】:

    标签: javascript jquery parameter-passing


    【解决方案1】:

    要将您自己的参数传递给这些回调并确保在这些回调中将this 正确设置为someObj,您可能需要额外的闭包:

    var optionObj = {
        duration: 300,
        easing: 'linear',
        complete: function() {
            someObj.onComplete(e);  // assumes 'e' is defined somewhere
        },
        step: function(now, fx) {   // jQuery automatically supplies these parameters
            someObj.onStep(e);      // so you need to pass your own instead
        }
    }
    

    【讨论】:

      【解决方案2】:

      尝试如下定义您的对象。从complete: someObj.onComplete 中删除(e),因为使用(e) 将调用该函数并将返回值分配给optionObj.completeoptionObj.step,即undefined

      var optionObj = {
          duration: 300,
          easing: 'linear',
          complete: someObj.onComplete, 
          step: someObj.onStep 
      }
      

      演示: http://jsfiddle.net/mL5Fy/

      【讨论】:

      • 注意:这将不会在两个回调中产生正确的this
      • 这是我做的第一件事,但仍然不确定
      猜你喜欢
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 2011-02-02
      • 2021-03-30
      • 1970-01-01
      相关资源
      最近更新 更多