我如何制作一个 alert() 来使用外部 JS 给出 if else 语句的结果

How do I make an alert() that gives the result of a if else statement using external JS

我是 HTML 和 JS 的新手,我正试图在网页上显示“早安”或“晚安”的按钮被按下时发出警报 问题是我需要在外部 JS 上执行此操作,但我在执行时遇到了麻烦。这是我目前的代码:

  var hour = new Date().getHours(); 
  var greeting;
  if (hour < 18) {
    greeting = "Good day";
  } else {
    greeting = "Good evening";
  }
  alert(greeting)
}

提前致谢!

编辑:我正在为一个项目做这个,它说 index.html 中不应包含任何脚本标签 这是我目前的 index.html:

<html>
<head>
<title>page</title>
<link rel="stylesheet" href="style.css" 
</head>
<body onload="loading()">
<div id="musicartists"></div>
<script src="script.js"></script>

<h1 onclick="greeting()">Greetings!</h1>
<button onclick="birthday()">My birthday</button>
<button onclick="myfunction()">Time based greeting</button>

<h3 id="musicartists">My favorite sports:</h3>
<p class="sports">Skiing</p>
<p class="sports">Swimming</p>


</body>
</html>

script.js:

// Creates an alert, when a specific button is pressed
function birthday() {
alert('September 9th');
}

// Creates an alert, when the body is loaded
function loading() {
alert("Page loaded successfully!");
}

function myFunction() {
  var hour = new Date().getHours(); 
  var greeting;
  if (hour < 18) {
    greeting = "Good day";
  } else {
    greeting = "Good evening";
  }
  alert(myFunction);
}

您可以将其全部塞入 onclick 处理程序中。

<button onclick="alert(new Date().getHours() < 18 ? 'Good Day' : 'Good Eventing')">Time based greeting</button>

// Creates an alert, when a specific button is pressed
function birthday() {
alert('September 9th');
}

// Creates an alert, when the body is loaded
function loading() {
alert("Page loaded successfully!");
}

function myFunction() {
  var hour = new Date().getHours(); 
  var greeting;
  if (hour < 18) {
    greeting = "Good day";
  } else {
    greeting = "Good evening";
  }
  alert(greeting);
}
<html>
<head>
<title>page</title>
<link rel="stylesheet" href="style.css" 
</head>
<body onload="loading()">
<div id="musicartists"></div>

<h1 onclick="greeting()">Greetings!</h1>
<button onclick="birthday()">My birthday</button>
<button onclick="myFunction()">Time based greeting</button>

<h3 id="musicartists">My favorite sports:</h3>
<p class="sports">Skiing</p>
<p class="sports">Swimming</p>

<script src="script.js"></script>

</body>
</html>

首先,最好将 <script> 标签放在 <body> 标签的底部,而不是顶部。

接下来一定要注意,myfunctionmyFunction是两个不同的变量; <button onclick="myfunction()">Time based greeting</button>指的是myfunction但实际功能是myFunction。大小写差别很大。

最后,alert(myFunction);实际上是将函数的源代码打印到屏幕上,而不是问候语。相反,你会想做 alert(greeting);.

以上就是我能找到的所有错误,希望对您有所帮助。