简体   繁体   中英

What is going wrong here?

i made this little script to learn javascript. but i keep getting unexpected token switch.. but hoe do is set switch the corect way??

html:

<p id="new">test<p>
    <input id="button" type="submit" name="button" value="enter" />

js:

var switch = true;

if (switch == false){
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = "Mijn Naam!";
    var switch = true;
};
} else {
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = "shiva";
    var switch = false;
};
}

how about:

<p id="new">test<p>
<input id="button" type="submit" name="button" value="enter" />

var clicked = false;

document.getElementById('button').onclick = function() {
  document.getElementById("new").innerHTML = clicked ? "shiva" : "Mijn Naam!";
  clicked = !clicked;
};

switch is a reserved word. You should use some variable name else.

By the way, your code is possible to be compressed as follows:

var switchOn = true;

document.getElementById('button').onclick = function() {
    document.getElementById("new").innerHTML = 
        switchOn ? "shiva" :"Mijn Naam!";
    switchOn = !switchOn;
}

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