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

只愿长相守 提交于 2021-02-18 08:29:21

问题


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

function termos() gives a true or false result;

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


回答1:


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.

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

So you can just say:

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



回答2:


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;
}



回答3:


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.

Set the id of 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.

Also, you can reduce your code like so:

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


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


来源:https://stackoverflow.com/questions/11456929/if-function-false-do-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!