javascript 如果然后语句javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15006723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if then statement javascript
提问by John Montague
I tried to do an "if/then" statement in javascript but the "then" command is being ignored. Any ideas on why?
我试图在 javascript 中执行“if/then”语句,但“then”命令被忽略。关于为什么的任何想法?
Specifically I want the form to be validated that the two text boxes are not blank and once that is validated I want a DIV ID = section2 to appear.
具体来说,我希望表单得到验证,两个文本框都不是空白,一旦验证,我想要一个 DIV ID = section2 出现。
function checkanswers() {
var fdet = document.wastheform;
if (fdet.question_type[0].checked) {
var elements = new Array("name","address");
var elements_name = new Array("name", "address");
for (var i = 0; i < elements.length; i++) {
if ($("#" + elements[i]).val() == "") {
err = "Please enter " + elements_name[i] + "";
alert(err);
return false;
}
}
$("#section2").show();
}
采纳答案by Mike Hogan
I'm assuming your "then" is the showing of the div. In which case I would do something like this:
我假设您的“然后”是 div 的显示。在这种情况下,我会做这样的事情:
function checkanswers() {
var fdet = document.wastheform;
if (fdet.question_type[0].checked) {
if(withoutValue("#name")) {
alert("Please enter name")
}
else if(withoutValue("#address")) {
alert("Please enter address")
} else {
$("#section2").show();
}
}
}
function withoutValue(selector) {
return $(selector).val() === "";
}
Is that what you're looking for?
这就是你要找的吗?
回答by Charlie Kilian
Your question implies that you want an if/then behavior (in Javascript, this is more properly referred to as an if/else statement), but the way you structured your code, there is no "then". Here is how the if statement should work:
你的问题暗示你想要一个 if/then 行为(在 Javascript 中,这更恰当地称为 if/else 语句),但是你构建代码的方式,没有“then”。下面是 if 语句的工作方式:
if ( condition )
{
// do something if the condition is true
}
else
{
// do something if the condition is false
}