首页 > 解决方案 > 单击一个按钮会触发其他具有相同事件功能的按钮

问题描述

我正在处理一个离子项目,并且在我的项目中,当我单击 1 个按钮时,其他按钮也会更改它们的值,因为它们具有相同的事件。但我想要相反,点击一个按钮应该只改变一个特定按钮的值。

HTML

<table class="student_list">
  <tr><ion-item *ngFor="let record of data">
        <ion-avatar slot="start">
          <img src="assets/student.png">
        </ion-avatar>
        <ion-label class="text2">{{record.name}}&ensp;{{record.id}}
        <span class="button1"><button (click)="toggleBackgroundColor()" ion-button [style.background-color]="hexColor" class="btn">{{text}}</button></span>
        </ion-label>
      </ion-item></tr>
    </table>

TS文件

public toggleBackgroundColor(): void {
   if(this.hexColor === '#1e90ff') { 
     this.hexColor = '#ff0000'
     this.text='A';
   } else {
    this.hexColor = '#1e90ff';
     this.text = 'P'
  }   }

标签: angularionic-frameworkangular7ionic4

解决方案


您应该在调用调用的特定标签的函数调用上放置一个标识符。

<button id="changeable" (click)="toggleBackgroundColor('changeable')" ion-button [style.background-color]="hexColor" class="btn">{{text}}</button>

和功能:

public toggleBackgroundColor(id): void {
      var element = document.getElementById(id);
      if(element.hexColor === '#1e90ff') { 
        element.hexColor = '#ff0000'
        element.text='A';
      } else {
        element.hexColor = '#1e90ff';
        element.text = 'P'
      }   }

推荐阅读