简体   繁体   中英

Javascript if clause won't work

I'm having trouble with a javascript function that needs to take a global variable into account.

It's kind of a control mechanism I would like to implement, but I can't seem to get it right.

Here's the relevant code

<script type="text/javascript">
var active = 0;

function SetEndTime(lngOpenPersonID,lngToDoID){
if(active = 0){
    alert('Time has been stopped');
}
else{
    var strURL = 'blabla';
    CallAJAXURL(strURL);
}
active = 0;
}
function SetStartTime(lngToDoID,lngToDoItemID,bitCountsForTotal){
if(active = 1){
    alert('Time has been started');
}
else{
    var strURL = 'blabla';
    CallAJAXURL(strURL);
}
active = 1;
}

When I call SetStartTime without doing anything else, I always get the alert. Is there something wrong with my syntax?

if (active == 0) {

You need 2 "=" characters to make a comparison operator. There's also === which performs an equality comparison without type promotion.

Your code is syntactically correct because an assignment operation is a valid expression. The first if statement you had:

if (active = 0) {

will never be true , because the value of the expression is always zero. The second one:

if (active = 1) {

conversely is always true because the value is always one.

它不是(alert = 1) ..它( alert == 1 ) ..您的情况表明它始终为真-您将警报分配为1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM