![](/img/trans.png)
[英]Javascript how to return value from function but not by return
[英]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.