繁体   English   中英

如何从javascript函数返回/传递值?

[英]how to return/pass value from javascript function?

一个相当琐碎的问题,如何在函数外返回或传递值?

代码如下:

function numberOfDivs(){
 var numberOfElements = $("#div").children().length; //this count how many divs exist
 return numberOfElements;
}

$("#element").click(function(){
  numberOfDivs();   
  console.log(numberOfElements);// here I need to return the number but getting error :(
});

非常感谢

$("#element").click(function(){
  var numberOfElements= numberOfDivs();   
  console.log(numberOfElements);
});

尝试

var numberOfElements= numberOfDivs();   
console.log(numberOfElements);

由于函数要返回值,因此在调用函数时,我们分配了一个变量以捕获结果

var numberOfElements;    
function numberOfDivs(){
    numberOfElements = $("#div").children().length; //this count how many divs exist
            }

    $("#element").click(function(){
             console.log(numberOfElements);// here I need to return the number but getting error :(
    });

一种方法是:像这样在全局范围内定义numberOfElements

var numberOfElements;
function numberOfDivs(){
 numberOfElements = $("#div").children().length; //this count how many divs exist
 return numberOfElements;
}

$("#element").click(function(){
  numberOfDivs();   
  console.log(numberOfElements);// here I need to return the number but getting error :(
});

或另一种方式是:将结果分配到一个变量中并使用该变量

$("#element").click(function(){
      var output = numberOfDivs();   
      console.log(output);// here I need to return the number but getting error :(
    });

尝试使用Callback函数,考虑以下情况:万一您的numberofDivs函数花时间返回值,则它不会给出适当的结果,因为Jquery是异步的。 参见此演示,了解如何使用回调返回数据CALLBACK DEMO

function AppendJson(callback) {
   var numberOfElements = "AppendJson";
   callback(numberOfElements)
}


AppendJson(function (ReturnValue) {
   alert(ReturnValue);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM