简体   繁体   中英

Trouble with setting greeting note with JS on HTML

I'm having trouble running a JS code from separate stylesheet on HTML page. Basically, I want to set an adequate greeting messages depending on the current hour of the day. I've searched and there are many ways to do it, but I am trying to get it work in this way and I didn't find a solution to this problem.

 window.onload = getGreeting(); function getGreeting() { var time = new Date(); var curHours = time.getHours(); if (curHours < 10) { document.getElementById("greeting").innerHTML = "Dobro jutro!"; } if else (curHours < 20) { document.getElementById("greeting").innerHTML = "Dobar dan!"; } if else { document.getElementById("greeting").innerHTML = "Dobro vece!"; } }; 
 <!DOCTYPE html> <head> <script type="text/javascript" src="LakaRukaDent.js"></script> </head> <body> <p id="greeting"></p> </body> 

When I run the HTML in Chrome the greeting doesn't appear. When I press f12 in Chrome it comes up with " Uncaught SyntaxError: Unexpected token < ", but I can't figure out why it doesn't work. I've checked syntax and functionality searching through the web but considering that I'm new with JS and HTML perhaps it could be some basic thing that I've skipped and I am not aware of.

Use else if instead of if else . Example from MDN:

if (x > 5) {

} else if (x > 50) {

} else {

}

Please find the fix below. window.onload expects a function reference not returned value of a function, that is why i remove parenthesis over there. Also there was syntax error with if else statement.

 window.onload = getGreeting; function getGreeting() { var time = new Date(); var curHours = time.getHours(); if (curHours < 10) { document.getElementById("greeting").innerHTML = "Dobro jutro!"; } else if (curHours < 20) { document.getElementById("greeting").innerHTML = "Dobar dan!"; } else { document.getElementById("greeting").innerHTML = "Dobro vece!"; } }; 
 <h1 id="greeting"></h1> 

First off, remove the parentheses from getGreeting when assigning to onload , as onload accepts a function. Also, you have syntax errors with your if statements. It should be else if not if else like so:

 window.onload = getGreeting; function getGreeting() { var time = new Date(); var curHours = time.getHours(); if (curHours < 10) { document.getElementById("greeting").innerHTML = "Dobro jutro!"; } else if (curHours < 20) { document.getElementById("greeting").innerHTML = "Dobro dan!"; } else { document.getElementById("greeting").innerHTML = "Dobro vece!"; } } 
 <p id="greeting"></p> 

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