[英]better solution about JS nesting if statement
Let's say there are 3 divs in my html. 假设我的html中有3个div。 Id's are: ID是:
I want first to load in data which is json from server on stepone div, if the return is '1' then print good on stepone div. 我想首先从stepone div上的服务器上加载json数据,如果返回值为“ 1”,则在stepone div上打印良好。
Then load in data on steptwo div, the data is json as well. 然后在steptwo div上加载数据,数据也是json。 So basically this is the process and the following is my code: 所以基本上这是过程,下面是我的代码:
$(document).ready(function(){
var loadingone = $.post("stepone.php");
.done(function(dataone){
objone = JSON && JSON.parse(dataone) || $.parseJSON(dataone); //get json return from server
if (objone.status == "1") {
$("#stepone").html("good");
var loadingtwo = $.post("steptwo.php")
.done(function(datatwo){
objtwo = JSON && JSON.parse(datatwo) || $.parseJSON(datatwo);
if (objtwo.status == "1"){
$("#steptwo").html("good");
}
else
{
$("#steptwo").html("bad");
}
});
}
else
{
$("#stepone").html("message" + objone.codeurl);
}
});
});
So as you can see the code contains nested if statement and it doesn't look very clear. 因此,如您所见,代码包含嵌套的if语句,看起来不太清楚。 I am wondering if there is a better solution for this? 我想知道是否有更好的解决方案? thx ===updata=== here's the code after i edited, is it right? thx === updata ===这是我编辑后的代码,对吗?
var loadingone = $.post("stepone.php");
.done(function(dataone){
objone = JSON && JSON.parse(dataone) || $.parseJSON(dataone);
if (objone.status != "1"){
$("#stepone").html("bad" + objone.codeurl")
}
else{
$("#stepone").html("good");
var loadingtwo = $.post("steptwo.php");
.done(function(datatwo){
objtwo = JSON && JSON.parse(datatwo) || $.parseJSON(datatwo);
if (objtwo.status != "1"){
$("#steptwo").html("bad");
}
else
{
$("#steptwo").html("good");
}
}
}
Negate your expressions. 否定您的表情。
Rather than following a pattern like: 而不是遵循以下模式:
if A {
if B {
if C {
do stuff
}
else error C
}
else error B
}
else error A
Try this: 尝试这个:
if !A {
error A
return
}
if !B {
error B
return
}
if !C {
error C
return
}
do stuff
This way, you keep the errors with their respective conditions, and you avoid deep nesting. 这样,您可以将错误与各自的条件保持一致,并避免深层嵌套。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.