[英]How to run a JavaScript file when a button is clicked in HTML?
我用 Phaser 3 創建了一個游戲。我將它作為 .js 文件存儲在我的工作目錄中。 我希望在 my.html 索引頁面上單擊開始按鈕時開始游戲。 我在這里做錯了什么?
我唯一需要做的就是讓游戲在單擊按鈕時運行,就像我在正文中包含了腳本一樣
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- Title of our Page -->
<title>Video Game</title>
<!-- Phaser 3 link here -->
<script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
<!-- CSS For our page -->
<style type="text/css">
html, body {
margin: 0;
width: 1000px !important;
height: 750px !important;
}
script {
width: 1000px !important;
height: 750px !important;
}
</style>
</head>
<body>
<script>
var skateGame = require('skateboarding.js');
</script>
<input type = "button" onclick = "skateGame" value = "Skateboarding" />
</body>
</html>
嘗試這個。
在您的.html文件中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- Title of our Page -->
<title>Video Game</title>
<!-- Phaser 3 link here -->
<script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
<!-- CSS For our page -->
<style type="text/css">
html,
body {
margin: 0;
width: 1000px !important;
height: 750px !important;
}
script {
width: 1000px !important;
height: 750px !important;
}
#startGame {
background-color: #4caf50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<input type="button" id="startGame" value="Start Game" />
<script src="skateBoarding.js"></script>
</body>
</html>
在skateBoarding.js
var startButton = document
.querySelector("#startGame")
.addEventListener("click", () => {
this.startGame();
});
// Function that start game
startGame = () => {
console.log("Game is starting");
};
讓我知道這個是否奏效。 並嘗試將您的 html 和 js 保存在單獨的文件中。
通過使用 onclick = "skateGame" 您要求 javascript 對 var SkateGame 做一些沒有意義的事情。 嘗試:
<button id="btn1" type="button"/>
<script type="text/javascript">
var myBtn= document.getElementById('btn1');
myBtn.onclick = function(){
Your javascript code
}
</script>
告訴我它是否有效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.