使“ For Loop”与“ forEach”相同

时间:2018-11-22 07:23:59

标签: javascript for-loop foreach

此人使用 For循环

单击另一个按钮后,它们不会变回播放按钮,而是停留在暂停状态。音频暂停没有问题,只是按钮由于某些原因没有变回原处。

https://jsfiddle.net/pezuLqvo/85/

enter image description here

function hideAllButtons(button) {
  const buttons = button.querySelectorAll(".play, .pause, .speaker");
  for (let i = 0; i < buttons.length; i += 1) {
    hide(buttons[i]);
  }
}

function pauseAllButtons(buttons) {
  for (let i = 0; i < buttons.length; i += 1) {
    if (isPlaying(buttons[i])) {
      showPlayButton(buttons[i]);
    }
  }
}

function showPauseButton(button) {
  const pause = getPause(button);
  pauseAllButtons(button);
  hideAllButtons(button);
  show(pause);
  button.classList.add("active");
}

看看这是如何设置的,您能否确定我将在上述代码中进行哪些更改以解决该问题?

此人使用 forEach

https://jsfiddle.net/pezuLqvo/84/

enter image description here

function hideAllButtons(button) {
  button.querySelectorAll(".play, .pause, .speaker").forEach(hide);
}

function pauseAllButtons() {
  const buttons = document.querySelectorAll(".playButton");
  buttons.forEach(function hidePause(button) {
    if (isPlaying(button)) {
      showPlayButton(button);
    }
  });
}

function showPauseButton(button) {
  const pause = getPause(button);
  pauseAllButtons();
  hideAllButtons(button);
  show(pause);
  button.classList.add("active");
}

1 个答案:

答案 0 :(得分:0)

这是答案:

https://jsfiddle.net/pezuLqvo/93/

function pauseAllButtons() {
  const buttons = document.querySelectorAll(".playButton");
  for (let i = 0; i < buttons.length; i += 1) {
    if (isPlaying(buttons[i])) {
      showPlayButton(buttons[i]);
    }
  }
}