繁体   English   中英

在PHP中调用按钮上的JS函数

[英]Calling JS function on button in PHP

我正在创建一个游戏,用户可以选择是否要与朋友或计算机对战

在我的PHP文件中,我创建了两个这样的按钮

<button id = "begin-game" onClick = "location.href='./g.php'" type = "button">START</button>
<button id = "begin-computer-game">Againts Ai</button>

第一个按钮按预期工作,但第二个按钮没有。 如何调用此方法,以便当用户单击“按Ai”按钮时,它将执行以下代码

这是我的js文件代码

const game = new Game();
document.getElementById('begin-game').addEventListener('click', function() {
  game.startGame();
  document.getElementById('begin-computer-game').style.display = 'none';
  this.style.display = 'none';
  document.getElementById('play-area').style.opacity = '1';
});
document.getElementById('begin-computer-game').addEventListener('click', function() {
  game.startComputerGame();
  this.style.display = 'none';
  document.getElementById('begin-game').style.display = 'none';
  document.getElementById('play-area').style.opacity = '1';
});
document.addEventListener('keydown', function(event) {
  game.handleKeydown(event);
});

现在我在控制台中收到此错误

你可以使用onclick

  1. addEventListener不会覆盖元素上的现有事件处理程序,而onclick会覆盖任何现有的onclick = function事件处理程序。

  2. addEventListener不适用于旧版本的Internet Explorer(> IE 9),它使用attachEvent(<IE 9),而onclick适用于所有浏览器。

<button id ="begin-computer-game" onclick ="functionA();">Againts Ai</button>

你的功能

functionA(){
   game.startComputerGame();
   this.style.display = 'none';
   document.getElementById('begin-game').style.display = 'none';
   document.getElementById('play-area').style.opacity = '1';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM