简体   繁体   English

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

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

A rather trivial question, how do I return or pass a value outside the function? 一个相当琐碎的问题,如何在函数外返回或传递值?

Code below: 代码如下:

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

many thanks 非常感谢

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

Try 尝试

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

As the function is to return a value, while we invoke the function we assigned a variable to capture the result 由于函数要返回值,因此在调用函数时,我们分配了一个变量以捕获结果

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

One way is : define numberOfElements in global scope like this : 一种方法是:像这样在全局范围内定义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 :(
});

Or another way is : assign the result in one variable and use that 或另一种方式是:将结果分配到一个变量中并使用该变量

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

Try using Callback functions, consider a scenario where incase your numberofDivs function takes time to return the value, it will not give the appropriate results as Jquery is an asynchronous. 尝试使用Callback函数,考虑以下情况:万一您的numberofDivs函数花时间返回值,则它不会给出适当的结果,因为Jquery是异步的。 See this demo for the use of callback to return the data CALLBACK DEMO 参见此演示,了解如何使用回调返回数据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