Set var to true/false in toggle function

2019-06-05 10:15发布

I have a button and I want my variable click to be set to true when the button is clicked, and false when the button is clicked again (I want toggle functionality).

When click == true, I want it to output clicked into the console and when click == false I want it to output not clicked.

var click = false

Here's my toggle function:

$('.button').toggle(
    function(){
        click = true;
        $('.bmw').show();

    }, function() {
        click = false;
        $('.bmw').hide();

    });

And what I want it to do:

if(click = true) {
    console.log('clicked');
} else {
    console.log('not clicked');
}

When I load the page the console shows not clicked but when I press the button it doesn't switch to true. The bmw objects** .bmw do however show and hide when I toggle the button so that seems to be working fine.

What am I doing wrong?

1条回答
祖国的老花朵
2楼-- · 2019-06-05 11:01

You are assigning not comparing the value of click

You should be doing this with == not =

if(click == true) {
    console.log('clicked');
} else {
    console.log('not clicked');
}

However you do not even need to use if(click == true). You can in fact just use if(click) instead.

EDIT: From what we discussed in the comments it looks like you were calling the if statement only once when the code was first run, not everytime you toggled. I suggest creating a seperate function with the if statement inside, then calling this method in both parts of the toggle.

查看更多
登录 后发表回答