Set var to true/false in toggle function

那年仲夏 提交于 2019-12-23 02:34:08

问题


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:


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.



来源:https://stackoverflow.com/questions/11432369/set-var-to-true-false-in-toggle-function

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