可以+ ++增加一个变量

时间:2018-03-08 04:14:27

标签: javascript angular typescript increment

Alrighty。所以我正在尝试创建一种录制歌曲播放次数的机制。所以在视觉上,我点击每首歌曲,但每次点击都不会增加播放变量。

这是TypeScript:

plays: number = 0;

  addPlay(song){
    song.plays = 0;
    song.plays++;
  }

HTML:

<ul> <!-- Each song on the album -->
    <li class="song-block"
        *ngFor='let song of songsToDisplay'
        (click)="getSong(song)"
        (mouseenter)="song.thumbsVisible=true"
        (mouseleave)="song.thumbsVisible=false">
      <div class="song-card"
           (click)="addPlay(song)">
        <p *ngIf="!song.isPlaying"
            class="song-number">{{song.tracknumber}}</p>
        <i *ngIf="song.isPlaying" class="fa fa-play fa-lg"></i>
        <p class="song-name">{{song.name}}</p>
        <p class="song-length">{{song.length}}</p>
        <div class="thumbs"
             *ngIf="song.thumbsVisible"> <!-- Thumbs section -->
          <i class="fa fa-thumbs-up fa-lg" [ngClass]="selected"
             (click)="thumbs(song)"
             >
          </i>
          <i class="fa fa-thumbs-down fa-lg" [ngClass]="selected"
             (click)="thumbs(song)"
             >
          </i>
        </div>

        <p class="plays">{{song.plays}}</p> <---- PLAYS
        <svg class="explicit"
            *ngIf="albumToDisplay.isExplicit === 'true'"
            viewBox="0 0 24 24"
            preserveAspectRatio="xMidYMid meet"
            focusable="false">
              <g class="style-scope iron-icon">
                <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z"></path></g></svg>
      </div>
    </li>
  </ul>

1 个答案:

答案 0 :(得分:2)

每次拨打0时,您都会将计数器重置为addPlay。所以变量确实在递增 - 但总是只有1

song.plays = 0;

尝试删除该行。

如果plays未在任何地方初始化,则可能需要将上述内容替换为此类内容;

if (song.plays === undefined) {
    song.plays = 0;
}