只需像这样在<body>
上添加一个onload
属性,无论如何:
<body onload="carsGoBrr()">
然后定义函数:
function carsGoBrr() {
var age = prompt("What is your age?");
if (Number(age) < 18) {
alert("Sorry, you are too young to drive this car. Powering off ");
} else if (Number(age) > 18) {
alert("Powering on. Enjoy the ride!");
} else if (Number(age) === 18 ) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
}
}
完整代码(按照我的编码风格;)):
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>javascript in HTML</h1>
<p>HElllllooooo</p>
<script type="text/javascript">
function carsGoBrr() {
var age = prompt("What is your age?");
if (Number(age) < 18) {
alert("Sorry, you are too young to drive this car. Powering off ");
} else if (Number(age) > 18) {
alert("Powering on. Enjoy the ride!");
} else if (Number(age) === 18 ) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
}
}
</script>
</body>
</html>