簡體   English   中英

javascript返回值始終未定義

[英]javascript return value is always undefined

我試圖檢索分隔函數的2個屬性,並在函數結束之前調試了那里的值,它們有一個值,但是返回值始終未定義,我不知道為什么!

.js文件

function STAAPlanlat(){
  alert ("the function");

  if (navigator.geolocation) {
    //we supposed to call the handlers of the expections 
    navigator.geolocation.watchPosition(function(position) {
      alert("show position ");
     //  x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;  
      var lat=position.coords.latitude;
      var lan=position.coords.longitude;    

      //x.innnerHTML=out
      alert(lat+"<"+lan);
      return lan;
    });

  } else {
    alert("error");
  }
}

我收到了有關lan和lat值的警報

但是當我調用分離的文件時,它返回未定義的返回值

 <!DOCTYPE html>
 <html>
 <head>
     <script type="text/javascript" src="STAAP1.2.js"> </script>

 <script type="text/javascript">
     function test(){
     var out=STAAPlanlat();     
     document.getElementById("STAAPlanlat").value = "lan is"+out;
     //document.writeln("lan is"+out);
     }
     </script>  
 </head>
 <body>
 <p id="STAAPlanlat">Test the division</p>
 <button onclick="test()">STAAPlanlat()</button>
 <button onClick="alertme()" >Alert</button>

 </body>
 </html>

您正在返回匿名函數,並且此值永遠不會分配給任何東西。 您可以使用回調來執行所需的操作。

// untested code, hope it works
function STAAPlanlat(callback){
    alert ("the function");
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(function(position) {
            var lat=position.coords.latitude;
            var lan=position.coords.longitude;  
            callback(lat, lan);
        });
    }
    else{
        alert("error");
    }
}

還有你的測試功能...

function test(){
    var out;
    STAAPlanlat(function(lat, lon) { out = lat; });
}

因為您不是從主函數返回它,而是從嵌入式匿名函數返回它,而該匿名函數對此沒有任何作用。 做這個:

function STAAPlanlat(){
var lat;
var lan;
alert ("the function");
if (navigator.geolocation) {
    //we supposed to call the handlers of the expections 
    navigator.geolocation.watchPosition(function(position) {
        alert("show position ");
        //  x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;   
        lat=position.coords.latitude;
        lan=position.coords.longitude;  

        //x.innnerHTML=out
        alert(lat+"<"+lan);
    });
    return lan;
}
else
    alert("error");
}

因為函數STAAPlanlat不返回任何值。 您的匿名函數返回lan但它是異步回調。 return lan;之前添加它return lan;

document.getElementById("STAAPlanlat").value = "lan is" + lan;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM