Trouble with If/Else Statements in Javascript

时间:2017-06-12 16:46:42

标签: javascript if-statement button

I am working on a basic pager system for my dad's dental office. Essentially I am recreating this device, but in a much prettier touch screen form using Kindles. Basically, the buttons have 3 state: Off, On, Flashing. SO the idea is that I want to host a JavaScript back end that all of the Kindles are set on. They can all send and receive updates. I'm having a surprising amount of issues a creating a button that goes through these three states.

I created a basic counter that displays in a button like this.

<body>
<script type="text/javascript">
var state = 0;
function onClick() {
    state += 1;
    document.getElementById("clicks").innerHTML = state;
};
</script>
<button type="button" onClick="onClick()">Click me</button>
<p>State : <a id="clicks">0</a></p>

</body></html>

But I am trying to build a function that will tell the style to loop from the 3rd state back to the first, and I didn't imagine I would have this much trouble. So I tested a few variations of if/else conditions, using the assumption that that the state variable was actually holding the value as the displayed numbers were increasing. it ended up looking something like this:

<script>
var state = 0;
function onClick() {
if (state = 0) {
    state += 1;
} else if (state = 1) {
    state += 1;
} else {
state -= 1;
}

but this doesn't function... Clearly I don't get how to use conditional statements... in the first example, is the state variable not actually storing the value? What am I doing wrong, is it syntax?

2 个答案:

答案 0 :(得分:3)

In IF-statements, you check for equality using == or ===. A single = is used purely for assignment.

答案 1 :(得分:0)

Change = to == = is for assignment only whereas == is for comaprison purposes