【问题标题】:button needs two clicks to collapse a div in html angular按钮需要单击两次才能折叠 html 角度中的 div
【发布时间】:2018-11-29 10:36:19
【问题描述】:

我有一个按展开和折叠功能分组的 div 列表,如下所示。它工作正常,除了我需要单击按钮两次才能打开另一个 div。第一次点击只会折叠第一个 div。

<div *ngFor="let item of data; let i = index">
      <button
        (click)="setIndex(i)"
      >
        <span
          [translate]=“item.title”
        ></span>

      </button>
      <div
        [class.collapse]='currentIndex !== i'
      >
        <div [innerHTML]=“item.description | translate"
        ></div>
      </div>
      <hr>

    </div>

我的打字稿功能如下所示。

setIndex(i) {
    this.currentIndex = this.currentIndex === -1 ? i : -1;
  }

我尝试将点击事件更改为 mousedown 或 keydown 但没有成功。

【问题讨论】:

  • 你为什么要使用这个逻辑:this.currentIndex === -1 ? i : -1?

标签: javascript html css angular typescript


【解决方案1】:

通过以下方式更改您的 setIndex 函数:

setIndex(i) {
   this.currentIndex = this.currentIndex === i ? -1 : i;
}

因为第一次点击会将 currentIndex 设置为 -1,所以它会折叠第一个 div (因为知道 currentIndex 与所有 i 值不同) 但你需要它i (新点击的i)也显示新的div。

如果当前显示 div 并且您再次单击它,(所以 currentIndex === i) 我们将其设置为 -1,因此它会折叠。

【讨论】:

    【解决方案2】:

    如下更改您的setIndex()。

    说明

    我们已经声明currentIndex = -1。

    当用户点击任何按钮时,我们必须检查currentIndex,如果它是-1,我们必须在currentIndex 中设置i 的值。

    现在我们有更多 2 个选项。如果用户一次又一次点击同一个按钮,我们必须检查i === currentIndex

    如果第一个 div 是打开的,那么最后一个是 currentIndex = 0,现在用户点击第三个按钮是 index is 2 现在首先我们必须设置 currentIndex = -1 and currentIndex = i

    html

    <div *ngFor="let item of data1; let i = index">
          <button (click)="setIndex(i)">
            <span>{{item.title}}</span>
          </button>
          <div [hidden]='currentIndex !== i'>
            <div>{{item.description}}</div>
        </div>
        <hr>
    </div>
    

    ts

    setIndex(i) {
        if (this.currentIndex === -1) {
            this.currentIndex = i;
        } else if (this.currentIndex === i) {
            this.currentIndex = i;
        } else {
            this.currentIndex = -1;
            this.currentIndex = i;
        }
    }
    

    注意:

    这里我使用[hidden] 只是一个例子。你可以用你的

    【讨论】:

    • 你的setIndex 函数没有意义。为什么要连续两次分配一个变量?为什么要将i 分配给已经包含该值的变量?
    • 最后一种情况不同。首先你点击第 0 行,所以 currentIndex 有 0 现在你点击第 3 行,所以 currentIndex 仍然有 0,因为你仍然要从最后一个 else 条件中分配值,因为前 2 个条件出错了
    猜你喜欢
    • 2010-12-04
    • 2017-09-23
    • 2014-08-08
    • 1970-01-01
    • 2019-04-01
    • 2019-05-30
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多