我刚刚在 Codecademy.com 上完成了对 JavaScript 的学习,我正在尝试一个带有 html 按钮的简单功能。我的问题是我想我不明白我学到的 JS 如何等同于可用代码,我搜索了这些论坛并尝试了 document.getElementById.onclick 方法,我尝试使用 onClick="adventure();" 在按钮本身,我无法得到任何工作。请向我解释如何将 JS 应用于按钮,以便它在浏览器中工作。谢谢你。
<!doctype html>
<html>
<head>
<script type="text/javascript">
document.getElementById("adv").onclick = adventure();
function adventure() {
if (confirm('I am ready to play!')) {
var age = prompt("What's your age?");
if(age < 18) {
console.log('I cannot stop you from playing, but do so at your own risk!');
} else {
console.log('You have a great challenge, ahead. Brace yourself.' + "\r\n");
}
console.log("You are walking down the street and you see Shawn beating up your friends and stealing their candy. You feel as though it is your duty to respond. You walk up to him and say, 'Hey, Shawn, knock it off!" + "\r\n");
console.log("Shawn glares at you." + "\r\n");
var choice1 = function() {
var userAnswer = prompt("Do you wish to fight?" + "\r\n");
if(userAnswer !== "yes" || userAnswer !== "no") {
console.log("You must choose 'yes' or 'no'.");
choice1();
} else if (userAnswer === "yes") {
console.log("As you go to kick Shawn, he grabs your leg and slams you to the pavement. As the world turns black and your eyes slowly close, you feel the end is near. You cry, and then perish. Goodbye!");
} else {
console.log("Good choice, weakling. By playing the coward you will survive. Now where's my beer?");
}
};
}
</script>
</head>
<body>
<input id="adv" type="button" onclick="adventure();" value="Start Your Adventure" />
</body>
</html>