jQuery Mutiple如果其他语句
问题描述:
我正在使用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>
有没有更好的方式来写这整个代码或者是这段代码好吗?
答
另一种方法是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;
}
答
你很可能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
情况下处理未知错误代码)
使用switch语句。 – brenners1302
你到底在找什么?你可以用多种方式编写这个功能,如果他们给你正确的结果,所有这些功能都可以“好”。 – mjuarez
..但是使用'if else'语句没有真正的问题 – Neilos