我正在研究这个简单的井字游戏应用程序,每当玩家点击按钮时,它将触发功能 markTheCell(按钮)传递按钮的ID。然后,此函数将向播放器发出字符串值和服务器的按钮ID。我将控制台日志放在客户端页面中,以查看是否正在传递有效值。但是当我尝试在服务器中记录它时,播放器的值变为对象Object并且按钮id未定义。我不知道我是否无法正确放置和使用参数。希望有人能提供帮助,因为我坚持这一点。
的index.html
<body>
<div class="col-lg-4"></div>
<div class="col-lg-4 jumbotron">
<h4>You are player <span id="name"></span></h4>
<button id="one" onclick="markTheCell(this.id)" class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button></br>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button></br>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
</div>
<div class="col-lg-4"></div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var player = "";
$(document).ready(function () {
socket.on('player', function (playerNo) {
player = playerNo;
$('#name').text(playerNo);
});
socket.on('hitAMark', function (player, button) {
console.log("in client hit a mark player "+ player);
console.log("in client hit a mark button "+ button);
$(button).text(player);
});
})
function markTheCell(button) {
socket.emit('mark', {player,button });
console.log("in markTheCell client hit a mark player "+ player);
console.log("in markTheCell client hit a mark button "+ button);
}
</script>
</body>
index.js
var player = 0;
io.on('connection', function(socket){
if(player==0){
player++;
socket.emit('player', "X");
console.log("Player "+ player +" is connected");
}else if(player==1){
player++;
socket.emit('player', "O");
console.log("Player "+ player +" is connected");
}
socket.on('disconnect', function(){
console.log('A user is disconnected');
});
socket.on('mark', function(player, button){
console.log("in server hit a mark button "+ player);
console.log("in server hit a mark player "+button);
io.emit('hitAMark', {player,button});
});
});
http.listen(3000, function(){
console.log('Server is listening on port 3000!');
});
答案 0 :(得分:1)
尝试发出{player:player,button:button}
代替{player,button}
。可能它可以工作。