简体   繁体   中英

Why does my javascript not work when I remove carriage returns?

Working javascript example is as follows...

<script>var count=1; function setColor(button) { var property = document.getElementById(button); if (count == 0) {property.style.color="red"
 count=1;}else{property.style.color="green"
 count=0;}}</script>

Broken javascript example is as follows...

<script>var count=1; function setColor(button) { var property = document.getElementById(button); if (count == 0) {property.style.color="red" count=1;}else{property.style.color="green" count=0;}}</script>

The html...

<a href="#" id="button" style= "color:red" onclick="setColor('button'); playlist.toggleShuffle();">SHUFFLE</a>

Any help understanding this would be great.

property.style.color="red" count=1; and property.style.color="green" count=0; are both not valid JavaScript. When you're not using carriage returns, you need a semicolon to delineate the end of the line after "red" and "green" .

What you're looking for is more like:

<script>var count=1; function setColor(button) { var property = document.getElementById(button); if (count == 0) {property.style.color="red"; count=1;}else{property.style.color="green"; count=0;}}</script>

This feature is referred to as semicolon insertion; you can read more about it at this link .

... however I'm really not sure why you'd want to do this, as this saves maybe a byte or two here and there and offers no performance benefit, while nuking most of the readability of your code.

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