Multiple If Statements in a Row with jQuery
I would like to add multiple if statements to a function. I am using YouTube's iFrame API to do different actions when the video is play or paused. I currently have the following code:
function onPlayerStateChange(newState)开发者_Python百科 {
console.log(newState);
if (newState.data == 1) {
//do something
return false;
} else {
//do something else
return false;
}
}
It works great when I only have the first if statement, but breaks when I add the else clause to it. How do you check for multiple conditions like this with jQuery?
Use a switch
on newState.data
, like this:
switch(newState.data){
case 1:
//do something
//break or return true/false
case 2:
//Do something else
break;
case 3:
break;
default:
//Do something when newState.data is NOT 1, 2 or 3
break;
}
Your code with the if ... else
is an "either-or" approach. It's not entirely clear to me what you're trying to do. However, the syntax is valid so it must be the logic that fails.
If you want to do multiple independent action, use sequential if
blocks, e.g.:
if (newState.data == 1) {
//do something
}
if (anotherCondition) {
//do something more
}
return false;
If multiple conditions need to be true:
if (newState.data == 1 && anotherCondition) {
//do something
return false;
}
精彩评论