【问题标题】:JQuery return a function to a variableJQuery将函数返回给变量
【发布时间】:2014-07-23 23:34:58
【问题描述】:

有什么方法可以设置一个变量等于一个函数,而不是变量等于函数,而是等于函数的返回值?

对此进行了一些搜索但没有成功,这很可能是因为我不知道如何表达这个问题,但感谢任何帮助,这就是我所拥有的:

不必在函数之后设置var ztype = zoom(),我是否可以将返回值分配给zoom而无需额外的代码行?

var zoom = function(){ //can be set to Full / percentage / Image / left empty for native image size
    var type = $('.carousel').attr('data-zoom');
    if(!type){
        type = $(that).attr('data-zoom');
    }

    return type;
}
var ztype = zoom();

【问题讨论】:

  • 可以将ztype定义为全局变量,然后在函数内部访问。

标签: javascript jquery


【解决方案1】:

如果我对您的理解正确,您正在尝试将变量设置为函数的结果。这应该可以满足您的期望;

var ztype = function(){ //can be set to Full / percentage / Image / left empty for native image size
    var type = $('.carousel').attr('data-zoom');
    if(!type){
        type = $(that).attr('data-zoom');
    }

    return type;
}();

【讨论】:

  • 啊,那么函数末尾的() 会做什么?
  • @Adjit 会立即执行函数
  • 是的,它会立即调用函数
  • 太棒了,不知道该如何表达这个问题,但我很高兴你们能理解。谢谢,我会接受的时候我会接受
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 2012-03-02
  • 2011-01-18
相关资源
最近更新 更多