Как l oop через массив одним нажатием кнопки? - PullRequest
1 голос
/ 09 июля 2020

Я хочу l oop по списку artists, и каждый раз, когда нажимается кнопка, я хочу, чтобы следующий исполнитель добавлялся в тег <p>.

let para = document.querySelector('p');

const artists = ['Atif Aslam', 'Nusrat Fateh Ali Khan', 'Kendrick Lamar', 'Travis Scot', 'JCole', 'Sidhu', 'Ataullah EsaKheilvi'];
let info = 'One of my top favorite artist is '


function myArt() {
  for (i = 0; i < artists.length; i++) {
    para.textContent = info + artists[i];
  }
}
<body>

  <button id="myArtists" onclick="myArt()"> Click To Find Out!</button>
  <p> </p>
</body>

Ответы [ 4 ]

1 голос
/ 09 июля 2020

Вам не нужно oop для того, что вы пытаетесь сделать. Вместо этого вы хотите отслеживать индекс для исполнителя и увеличивать индекс каждый раз, когда вызывается myArt().

let para = document.querySelector('p');

const artists = ['Atif Aslam', 'Nusrat Fateh Ali Khan', 'Kendrick Lamar', 'Travis Scot', 'JCole', 'Sidhu', 'Ataullah EsaKheilvi'];

const info = 'One of my top favorite artist is ';

let artistIndex = 0;

function myArt() {
  if(artistIndex < artists.length) {
    para.innerText = info + artists[artistIndex];
    artistIndex++;
  }
}
<button id="myArtists" onclick="myArt()"> Click To Find Out!</button>
<p></p>
0 голосов
/ 09 июля 2020

Вам не нужен al oop. Просто используйте глобальную переменную для текущего указателя индекса.

Простой способ, чтобы это работало, плюс для кругового «цикла» при нажатии на кнопку.
Вы можете использовать модуль index % artists.length, который будет отразить индекс:

const $p = document.querySelector('p');
const textPrefix = 'One of my top favorite artist is: ';
const artists = ['Atif Aslam', 'Nusrat Fateh Ali Khan', 'Kendrick Lamar', 'Travis Scot', 'JCole', 'Sidhu', 'Ataullah EsaKheilvi'];
let currentArtistIndex = 0;

function nextArtist() {
  $p.innerText = `${textPrefix}${artists[currentArtistIndex++ % artists.length]}`; 
}
<body>
  <button id="myArtists" onclick="nextArtist()"> Click To Find Out The Next Artist!</button>
  <p> </p>
</body>
0 голосов
/ 09 июля 2020

Вам действительно не нужно l oop через него, если вы просто отслеживаете индекс. Вы можете использовать глобальную переменную или закодировать ее как атрибут, например:

const artists = ['Atif Aslam', 'Nusrat Fateh Ali Khan', 'Kendrick Lamar', 'Travis Scot', 'JCole', 'Sidhu', 'Ataullah EsaKheilvi'];
let info = 'One of my top favorite artist is '

const setup = () => {

  const myArtists = document.querySelector('#myArtists');
  myArtists.addEventListener('click', myArt);

};

const myArt = (event) => {
  const button = event.target;
  
  const previousIndex = button.hasAttribute('currentIndex') ? parseInt(button.getAttribute('currentIndex'),10) : -1;
  
  const currentIndex = previousIndex >= artists.length - 1 ? 0 : previousIndex + 1;
  
  button.setAttribute('currentIndex', currentIndex);
  
  let para = document.querySelector('p');
  para.textContent = info + artists[currentIndex];
}

window.addEventListener('load', setup);
<button id="myArtists"> Click To Find Out!</button>
<p> </p>
0 голосов
/ 09 июля 2020

Ваша проблема не в зацикливании, а в том, что вам не нужен al oop. Вам просто нужна переменная как указатель на go через ваш массив как таковой.

  let para = document.querySelector('p');

  const artists = ['Atif Aslam', 'Nusrat Fateh Ali Khan', 'Kendrick Lamar', 'Travis Scot', 'JCole', 'Sidhu', 'Ataullah EsaKheilvi'];
  let info = 'One of my top favorite artist is '

  //Array pointer
  let counter = 0;
  function myArt() {
    para.textContent = info + artists[counter++];
    if (counter == artists.length) {
      //Rest pointer
      counter = 0
    }
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...