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

如何从javascript函数返回/传递值?,javascript,jquery,Javascript,Jquery,一个相当简单的问题,如何在函数外部返回或传递值 代码如下: function numberOfDivs(){ var numberOfElements = $("#div").children().length; //this count how many divs exist return numberOfElements; } $("#element").click(function(){ numberOfDivs(); console.log(numberOfEleme

一个相当简单的问题,如何在函数外部返回或传递值

代码如下:

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);
});

由于函数返回一个值,在调用函数时,我们分配了一个变量来捕获结果,其中一种方法是:在全局范围内定义
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 :(
    });

试着使用回调函数,考虑一个场景,在这种情况下,您的NuffoDIVS函数需要花费时间来返回值,因为jQuery是异步的,所以它不会给出适当的结果。请参阅此演示,了解如何使用回调返回数据


这是一个异步函数的回调。您不能直接返回任何内容。@medzi,这是非常基本的内容,也许您应该选择一个教程,进一步熟悉该语言。@Danilo,您在哪里看到异步调用?这是一个存储
numberOfDivs()
返回的值的简单问题。单击
方法将事件侦听器附加到id
元素的节点,因此async@Danilo,只要被调用方(
numberOfDivs()
)本身不是异步的(事实并非如此),那么异步调用方就不是问题。
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 :(
    });
function AppendJson(callback) {
   var numberOfElements = "AppendJson";
   callback(numberOfElements)
}


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