I am trying to make a function which is call when a
"Try it" button is clicked and a loop run inside the function where a word is change using loop
I am new to JavaScript but old to programming.
It's kind of confusing if compared with C or C++
<!DOCTYPE html>
<html>
<head>
<style>
#demo {
font-size: 600%;
color: red;
}
</style>
<script>
function changing() {
var my = undefined;
for (count = 1; count < 3; count++) {
if (count == 1) {
my = LIFE;
document.getElementById('demo').innerHTML = my;
} else if (count == 2) {
my = STYLE;
document.getElementById('demo').innerHTML = my;
} else if (count == 3) {
{
break;
}
}
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<div id="demo">AWESOME</div>
<button type="button" onclick="changing()">Try it</button>
</body>
</html>
Error parts :
else if (count == 3) {
{
You opened 2 curly braces
also use "LIFE"
instead of LIFE
and "STYLE"~ instead of
STYLE`
function changing() { var my = undefined; for (count = 1; count < 3; count++) { if (count == 1) { my = "LIFE"; document.getElementById('demo').innerHTML = my; } else if (count == 2) { my = "STYLE"; document.getElementById('demo').innerHTML = my; } else if (count == 3) { break; } } }
<!DOCTYPE html> <html> <head> <style> #demo { font-size: 600%; color: red; } </style> </head> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <div id="demo">AWESOME</div> <button type="button" onclick="changing()">Try it</button> </body> </html>
Remember about quotation marks when using strings
. Else, it will be treated as a variable
. And since it hasn't been declared - function will throw errors.
function changing() { var my; for (count = 1; count < 3; count++) { if (count == 1) { my = 'LIFE'; document.getElementById('demo').innerHTML = my; } else if (count == 2) { my = 'STYLE'; document.getElementById('demo').innerHTML = my; } else if (count == 3) { break; } } }
#demo { font-size: 600%; color: red; }
<h1>My First Web Page</h1> <p>My first paragraph.</p> <div id="demo">AWESOME</div> <button type="button" onclick="changing()">Try it</button>
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.