首页 > 解决方案 > Ionic 3 - 如果同时激活(JS)

问题描述

我有一个小问题,我找不到解决方案,

我在这里有这个小功能:

Clicked(){
       for (let i = 0; i < 5; i++) {
          if (this.ShareProvider.ValueFonction(i)) {
            alert(i)
          }
        }
}

有 6 个按钮,我想要做的是当我单击一个按钮时,alert()功能将启动。问题是当我运行程序时,它会连续显示 6 个警报。我试图写不同的方式,但同样的问题。

if (this.ShareProvider.ValueFonction(1)) {
  alert(1)
}
if (this.ShareProvider.ValueFonction(2)) {
  alert(2)
}
if (this.ShareProvider.ValueFonction(3)) {
  alert(3)
}
if (this.ShareProvider.ValueFonction(4)) {
  alert(4)
}
if (this.ShareProvider.ValueFonction(5)) {
  alert(5)
}
if (this.ShareProvider.ValueFonction(6)) {
  alert(6)
}

或者

if (this.ShareProvider.ValueFonction(1)) {
  alert(1)
}
if (this.ShareProvider.ValueFonction(2)) {
  alert(2)
}
if (this.ShareProvider.ValueFonction(3)) {
  alert(3)
}
if (this.ShareProvider.ValueFonction(4)) {
  alert(4)
}
if (this.ShareProvider.ValueFonction(5)) {
  alert(5)
}
if (this.ShareProvider.ValueFonction(6)) {
  alert(6)
}

感谢您的关注

标签: javascriptfunctionif-statementbuttonionic-framework

解决方案


您可以通过多种方式做到这一点,我建议您在 Ts 模板上创建一个数组,然后在 Html 中的 ngFor 中调用它们,并使用(单击)函数使用当前索引调用警报。例如:

在 TS 模板中:

在类的顶部声明一个长度为 var 的数组,例如:

array= new Array(5);

提醒索引的功能:

clicked(i){
     alert(i);
}

并在 html 模板中:

  <div *ngFor="let a of array; let i = index">
    <button (click)="alert(i)> Click me </button>
  </div>

那将根据元素索引显示警报


推荐阅读