-2
我正在嘗試構建一個井字遊戲,用戶首先點擊哪個玩家他想成爲玩家,然後點擊他想玩的棋盤上的廣場。我遇到的問題是更改用戶點擊的方塊的背景。因爲我不知道用戶點擊哪個方塊,所以我無法弄清楚如何改變背景的風格,因爲廣場的id/class是未知的。在JavaScript中更改未知元素的樣式
我不能說:
document.getElementById("randomId").style.backg round
,因爲我不知道用戶會點擊該廣場。下面的代碼:
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe Game</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style type="text/css">
#buttons{
margin-top: 50px;
}
#x{
margin-left: 10px;
}
#table{
margin-top: 15px;
background: gray;
table-layout: fixed;
width: auto;
width: 250px;
height: 250px;
}
</style>
</head>
<body>
<div class="container" id="buttons">
<h2 id="h2">Choose your team!</h2>
<button onclick="myFunctions()" type="button" class="btn btn-default"><span
style="font-weight: bold; font-size: 110%;">O</span></button>
<button type="button" id="x" class="btn btn-default"><span class="glyphicon glyphicon-remove"></span>
</button>
<table id="table" class="table table-bordered">
<tbody>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var master = false;
var servant = false;
function myFunctions(){
master = true;
}
function myFunction() {
if (master == true) {
}
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
你爲什麼要使用JavaScript,而不是jQuery的任何原因?我只問這是因爲boostrap的js需要jquery反正 – indubitablee
是的,我只是想練習我的JavaScript。我在該函數的定義中加入了什麼? this.style.background? – Aaronpd1