Javascript if (function() === false){ 这样做}

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11456929/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:54:28  来源:igfitidea点击:

if (function() === false){ do this}

javascriptjqueryif-statement

提问by Souza

i'm trying to solve this issue, i'm relatively new to javascript, so:

我正在尝试解决这个问题,我对 javascript 比较陌生,所以:

function termos() gives a true or false result;

函数 termos() 给出一个真或假的结果;

probably the solution to this is simple, but can't get to it. Is it possible to do this? i wrote this code just to exemplify my doubt

可能对此的解决方案很简单,但无法解决。是否有可能做到这一点?我写这段代码只是为了说明我的怀疑

function termos() {
  if($('.terms').is(':checked')) {
    return true;
  } else {
    return false;
  }
}

can i use

我可以用吗

} else if(termos() === false) {
  alert('please agree with terms');
  return false;
}

This doesn't work

这不起作用

回答by vinnybad

From what I understand you want to see if termos() returns true or false and in this case, when it returns false you want to go through a block of code.

据我了解,您想查看 termos() 返回 true 还是 false,在这种情况下,当它返回 false 时,您想查看一段代码。

You can use falsy / truthy evaluations(http://11heavens.com/falsy-and-truthy-in-javascript)

您可以使用虚假/真实评估http://11heavens.com/falsy-and-truthy-in-javascript

So you can just say:

所以你只能说:

if ( termos() ) {
  // when its true
} else {
 // when its false
}

回答by anAgent

Since you are using a class to set the jQuery object, you will get conflicting results if you have more than one item with that class. I am assuming based on the lack of detail from your question that this might be the case.

由于您使用一个类来设置 jQuery 对象,如果您有多个项目与该类,您将得到相互冲突的结果。我假设基于您的问题缺乏细节,可能是这种情况。

Set the idof the checkbox so you can correctly select the element. Also, it is best to set the parent container so that the jQuery isn't searching the entire DOM.

设置id复选框的 ,以便您可以正确选择元素。此外,最好设置父容器,以便 jQuery 不会搜索整个 DOM。

Also, you can reduce your code like so:

此外,您可以像这样减少代码:

function termos(){
  return $('#Agree',"#ParentContainer").is(':checked');
}


if(!termos()){
  alert('please agree with terms');
}

回答by Souza

This solved my problem. Thanks to who tried to help.

这解决了我的问题。感谢谁试图提供帮助。

function termos(){
        if ($('.checky3').is(':checked')){
            return 1;
        }
    }

if (termos() !== 1){
        $('.checky3').css('border','solid 1px red');
        return false;
}