javascript - 知道点击了哪个按钮的方法 - Angular 5
问题描述
我正在开发一个测验应用程序,对于给定的问题有 4 个选项。我已经编写了一个函数来验证单击的选项是正确答案还是错误。我在知道用户选择了哪个选项时遇到了问题,我想使用 CSS 将其设置为 - 如果选择了错误的选项,则单击选项会变成红色,正确的选项会变成绿色,反之亦然。
HTML:
<div *ngFor="let actiVar of activeArray ;let j = index" >
{{actiVar.QuestionID}}.{{actiVar.Question}}
<br>
<br>
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0]) ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<br>
<br>
<button type="button" name="s" id="two" (click)="filterAnswer(actiVar.OP[j+1]) ; getColor(actiVar.OP[j+1])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button> <br>
<br>
<button type="button" name="s" id="three" (click)="filterAnswer(actiVar.OP[j+2]) ; getColor(actiVar.OP[j+2])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button> <br>
<br>
<button type="button" name="s" id="four" (click)="filterAnswer(actiVar.OP[j+3]) ; getColor(actiVar.OP[j+3])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
<br>
</div>
我已经getColor
为所选选项设置了一个 func onclick,但它的作用是,如果用户选择了错误的选项,它会将所有 4 个选项变为红色,反之亦然。它并没有专门将单击的选项变为红色。
getColor(j: any) {
if (j == this.activeArray[0].isRight) {
this.buttonColor = 'green';
}
else {
this.buttonColor = 'red';
}
}
this.activeArray[0].isRight
是从 JSON 中检索到的正确答案。我知道我将不得不使用id
按钮上的单个标签来知道单击了哪个选项按钮,但我没有运气在 stackoverflow 上找到正确的逻辑。
解决方案
您可以使用Template reference variables
-> https://angular.io/guide/template-syntax#ref-vars
<button #buttonRef1 type="button" (click)="filterAnswer(actiVar.OP[j+0], buttonRef1)" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<button #buttonRef2 type="button" (click)="filterAnswer(actiVar.OP[j+1], buttonRef2)" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button>
<button #buttonRef3 type="button" (click)="filterAnswer(actiVar.OP[j+2], buttonRef3)" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button>
<button #buttonRef4 type="button" (click)="filterAnswer(actiVar.OP[j+3], buttonRef4)" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
过滤器答案:
filterAnswer(answer: string, button: HTMLButtonElement) {
// Do logic here
button.style.backgroundColor = desiredColor; // example: "#f00"
}
推荐阅读
- python - Python 列表是否支持浮点数?什么时候需要浮点数不能做的整数?
- javascript - 禁用选择元素中的一个选项并启用其他选项
- node.js - 如何通过带有 swagger-client 的 put 方法发送请求正文参数
- mysql - 加入时如何让 MySQL 优化器首先使用我的索引?
- html - 从 SQL 数据库中选择某些 id 并将它们与其他 id 区别对待
- neural-network - 当添加一个新的节点基因时,是给它一个全局的还是局部的新编号?整洁的
- scylla - 创建包含非关键属性的全局二级索引
- powershell - Import-Csv 和 Set-MailContact:如何将 -ExtensionCustomAttribute1 设置为多个值
- javascript - 使用 Javascript 在 Chrome Selenium 中打开新标签时,浏览器滑到底部
- apache - Apache 可以同时设置为正向代理和反向代理吗?