Your Problem?
Well first off, your if statement contains an =
. an if statement must be evaluated with an ==
, although you should avoid that, as it doesn't check typing.
This is called Type Coercion. More on that here-
https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion
You should always try to use ===
when you can. This is represented in the example below.
if (x === 9) {
console.log("x is equal to 9.")
}
In newer javscript versions, you should try to use let
instead of var
.
Solution-
<p id="hExample">Hello my world </p>
<script>
let jExample = document.getElementById("hExample").innerHTML;
let jElements = jExample.split(" ");
for (let y = 0; y < jElements.length; y++) {
document.getElementById("hExample").innerHTML += '<span id=' + y + '>' + jElements[y] + " " + "</span> ";
}
document.getElementById('hExample').onclick = changeColor;
function changeColor() {
if (document.getElementById("hExample").style.color === "white") {
document.getElementById("hExample").style.color = "red";
} else {
document.getElementById("hExample").style.color = "white";
}
}
</script>
As you can see, the only logic that was wrong, was your if statement.
Remember:
Always use ===
and not =
in your if statements.
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…