Javascript javascript如果条件&&条件不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11446323/
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
javascript if condition && condition doesn't work
提问by Ivo San
the AND && operator doesn't work, but when i replace it with an OR || operation it is workin, why? I just used OR || operator for testing, what i need is an && operator. Please help. thanks
AND && 运算符不起作用,但是当我用 OR || 替换它时 运行正常,为什么?我刚用过 OR || 用于测试的运算符,我需要的是 && 运算符。请帮忙。谢谢
function validate() {
if ((document.form.option.value == 1) && (document.form.des.value == '')) {
alert("Please complete the form!");
return false
} else return true;
}
i also tried nested if but it doesn't work too
我也试过嵌套 if 但它也不起作用
if(document.form.option.value==1)
{
if(document.form.des.value=='')
{
alert ("Please complete the form!");
return false
}
}
回答by JaredPar
It sounds like ||
is what you are looking for here. The &&
operator is only true if both the left and right side of the &&
are true. In this case you appear to want to display the message if the value is 1
or empty. This is exactly what the ||
operator is for. It is true if either the left or right is true
这听起来像是||
你在这里寻找的东西。&&
只有当 的左侧和右侧都为真时,运算符才&&
为真。在这种情况下,如果值为1
或为空,您似乎想要显示消息。这正是||
运营商的用途。如果左或右为真,则为真
回答by MJ Fathinia
If Or operator is working, means there are some javascript errors in your second part of condition. check document.form.des.value=='' (maybe just open your javascript console in Chrome/Firefox/IE8+)
如果 Or 操作符正在工作,则意味着您的第二部分条件中存在一些 javascript 错误。检查 document.form.des.value=='' (也许只是在 Chrome/Firefox/IE8+ 中打开你的 javascript 控制台)
回答by Naren Karthik
its because one of the conditions specified above returns false and loop breaks. Is you use OR ,only one must be validated and returns true.. check your code for both the conditions.
这是因为上面指定的条件之一返回 false 并且循环中断。您是否使用 OR ,只有一个必须经过验证并返回 true .. 检查您的代码是否符合这两个条件。