Can a program have a few IFs and only one Else structures?
When I was doing some JQuery and PHP,
I noticed the开发者_StackOverflow If-else patterns were treated differently and varied from one language to another.Say I got a simple input text field in a HTML
and I was using some Ifs and Elses to check the value input into the text field.Text: <input type="text" name="testing"/>
In JQuery, I got some codes as follows:
if($("#testing").val()==1){
//do something
}
if($("#testing").val()=="add"){
//do something
}
else{
//do something
}
if($("#testing").val()=="hello"){
//do something
}
How come JQuery and PHP treated the Else statement differently?
I mean in JQuery, the third If statement was still proceeded even if it had gone to the Else statement, but it stopped after the Else statement when I repeated the code in PHP script.Your jQuery code is not how it should be, first of all, you are missing the id in your text field that you are checking in jquery:
<input type="text" name="testing" id="testing" />
And then you need elseif
structure and else
should go last:
if($("#testing").val()==1){
//do something
}
else if($("#testing").val()=="add"){
//do something
}
else if($("#testing").val()=="hello"){
//do something
}
else{
//do something
}
The else
executes if none of the previous conditions resolved to true.
the 3rd if is going to be proceeded, unless you make it:
else if($("#testing").val()=="hello"){
Explaination of if
//First If block is executed
if($("#testing").val()==1){
//do something
}
//This if will be executed separately from the previous
if($("#testing").val()=="add"){
//do something
}
else{
//do something
}
//This will also execute separately
if($("#testing").val()=="hello"){
//do something
}
In order to properly chain multiple exclusive if statements use "else if"
//First If block is executed
if($("#testing").val()==1){
//do something
}
//This if will be executed only if the first if is not
else if($("#testing").val()=="add"){
//do something
}
//else maintains standard usage as the final option
else{
//do something
}
//This will also execute separately
if($("#testing").val()=="hello"){
//do something
}
精彩评论