2015-10-06 214 views
-1

我正在使用jQuery編寫下面的代碼。我的代碼找到用戶的地理位置和處理錯誤,我已經使用多個if else語句jQuery Mutiple如果其他語句

<script> 
$(function() { 
    var error = $('#errDiv'); 
    $('#btnFindLoc').click(function() { 
     if (Modernizr.geolocation) { 
      navigator.geolocation.getCurrentPosition(currentPosition, positionError); 
     } 
     else { 
      error.html("GeoLocation API of HTML 5 is not supported"); 
     } 
    }); 

    function currentPosition(currentPos) { 
     var coordinates = currentPos.coords; 
     $('#lati').text(coordinates.latitude); 
     $('#longi').text(coordinates.longitude); 
     var googleMap = $('#gMap'); 
     googleMap.attr("href", "http://maps.google.com/maps?q=" + coordinates.latitude + "," + coordinates.longitude); 
    } 

    function positionError(errCode) { 
     if (errCode.code==0) { 
      error.html("Unknown Error - has occured"); 
     } 
     else if (errCode.code==1) { 
      error.html("Permission Denied - By the user"); 
     } 
     else if (errCode.code==2) { 
      error.html("Position/Location Unavailable"); 
     } 
     else if (errCode.code == 3) { 
      error.html("Timeout"); 
     } 
    } 
}); 
</script> 

有沒有更好的方式來寫這整個代碼或者是這段代碼好嗎?

+0

使用switch語句。 – brenners1302

+0

你到底在找什麼?你可以用多種方式編寫這個功能,如果他們給你正確的結果,所有這些功能都可以「好」。 – mjuarez

+0

..但是使用'if else'語句沒有真正的問題 – Neilos

回答

0

另一種方法是switch語句。儘管如此,我不確定它是如何改變的。對於你的代碼,它想這樣:

switch (errCode.code) { 
    case 0: 
     error.html("Unknown Error - has occured"); 
     break; 
    case 1: 
     error.html("Permission Denied - By the user"); 
     break; 
    case 2: 
     error.html("Position/Location Unavailable"); 
     break; 
    case 3: 
     error.html("Timeout"); 
     break; 
    } 

該開關還允許你指定一個默認選項。你可以做的另一件事是以同樣的方式處理兩個案例。

switch (errCode.code) { 
    case 0: 
     error.html("Unknown Error - has occured"); 
     break; 
    case 1: 
     error.html("Permission Denied - By the user"); 
     break; 
    case 2: 
     error.html("Position/Location Unavailable"); 
     break; 
    case 3: 
    case 4: 
    case 5: 
     error.html("Timeout"); 
     break; 
    default: 
     error.html("Some other error"); 
     break; 
    } 
0

你很可能switch聲明:

function positionError(errCode) { 
    switch(errCode.code) { 
     case 0: 
      error.html("Unknown Error - has occured"); 
     break; 

     case 1: 
      error.html("Permission Denied - By the user"); 
     break; 

     case 2: 
      error.html("Position/Location Unavailable"); 
     break; 

     case 3: 
      error.html("Timeout"); 
     break; 

     default: 
      error.html("Unknown Error"); 
     break; 
    } 
} 

(我添加了一個default情況下處理未知錯誤代碼)