You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular问答应用:如何获取选中按钮值以计算得分

问题分析与解决方案

核心问题

  • 循环生成的按钮共用同一个id="idx",DOM中id必须唯一,document.getElementById("idx")只会返回第一个匹配的元素,无法获取用户实际点击的选项。
  • 直接操作DOM不符合Angular的开发规范,应该通过数据绑定传递选中值。

修改步骤

1. 调整HTML模板

移除重复的id属性,点击事件传递当前选中的首都值:

<h1>Quiz</h1>
<div *ngIf="saveCont && saveCap " class="quescard">
    <form >
      <h1>What is the capital of {{saveCont[userIndex]}}</h1><br>
      <li *ngFor="let cap of options">
        <button type="button" class="btn btn-primary btn-block btn-lg" (click)="checkoptions(cap)">{{cap}}</button>
      </li>
     
      <button (click)="res()">Submit</button>
    </form>
</div>

2. 修改TypeScript逻辑

接收点击传递的选中值,直接和正确答案比较:

correct(selectedCap: string) {
  if (selectedCap === this.saveCap[this.userIndex]) {
    this.score += 1;
    console.log(true);
    console.log(this.score);
  }
}

checkoptions(selectedCap: string) {
  this.correct(selectedCap);
  this.userIndex++;
  this.arrayDel();
  this.arrayform();
  this.shuffle();
}

说明

这种方式通过事件绑定直接传递用户选中的选项值,既符合Angular的响应式开发思路,也避免了DOM操作带来的问题,同时保证了代码的可维护性。

内容的提问来源于stack exchange,提问作者renu manwani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:42:02