如何解决Uncaught ReferenceError:未在HTMLButtonElement.onclick

时间:2019-05-24 18:54:06

标签: html angular typescript

我正在尝试用角度编写岩石,纸张,剪刀游戏,但似乎无法使onclick方法发挥作用。

我听说这是一个范围界定问题,但似乎无法理解/应用我所写的内容。

这是我的html代码

<button class="play rock" type="button" onclick="play('rock')"></button>

这是我的ts脚本

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-rps-game',
  templateUrl: './rps-game.component.html',
  styleUrls: ['./rps-game.component.scss']
})
export class RpsGameComponent implements OnInit {

  loses: number;
  wins: number;

  constructor() { }

  ngOnInit() {
  }
  play(userChoice: string) {
    document.getElementById('player').innerHTML = '';
    document.getElementById('opponent').innerHTML = '';
    document.getElementById('results').innerHTML = '';

    const computerChoicer = Math.random();
    let computerChoice = '';
    if (computerChoicer < 0.34) {
      computerChoice = 'rock';
    } else if (computerChoicer <= 0.67) {
      computerChoice = 'paper';
    } else {
      computerChoice = 'scissors';
    }

    const winner = this.compare(userChoice, computerChoice);
    document.getElementById('results').innerHTML = winner;
    document.getElementById('wins').innerHTML = String(this.wins);
    document.getElementById('loses').innerHTML = String(this.loses);
  }

  compare(choice1, choice2) {
    if (choice1 === choice2) {
      return 'The result is a tie!';
    } else if (choice1 === 'rock') {
      if (choice2 === 'scissors') {
        this.wins++;
        return 'rock wins. rock on.';
      } else {
        this.loses++;
        return 'sorry. paper wins.';
      }
    } else if (choice1 === 'paper') {
      if (choice2 === 'rock') {
        this.wins++;
        return 'paper wins';
      } else {
        this.loses++;
        return 'sorry. scissors win.';
      }
    } else if (choice1 === 'scissors') {
      if (choice2 === 'rock') {
        this.loses++;
        return 'sorry. rock wins';
      } else {
        this.wins++;
        return 'scissors win';
      }
    }
  }

}

未捕获的ReferenceError:播放未定义     在HTMLButtonElement.onclick(((index):1)

2 个答案:

答案 0 :(得分:0)

onclick="play('rock')不是Angular所了解的。请改用(click)="play('rock')"

<button class="play rock" type="button" (click)="play('rock')"></button>

您可能想进一步了解角度:https://angular.io/guide/component-interaction


基本上是:

  • <button [title]="myTitle">这样的方括号绑定是INPUT绑定,它将绑定myTitle property on your class to the title HTML attribute. This is a one-way binding and the myTitle`属性,无法通过按钮进行更新。
  • 甚至发生are an OUTPUT binding and will (in this case) run the someFn()function when the点击之类的肢体绑定。

这两个也可以结合起来用于在某些组件上进行双向绑定,但是需要以特殊的方式来构建它们以进行处理。

答案 1 :(得分:-1)

您必须使用[click]或click,因为Angular并未定义onclick,并且也不会采用您在Angular组件中定义的特定方法。

因此,它应该看起来像这样:

<button class="play rock" type="button" click="play('rock')"></button>

应该解决