1

let phrases = [
    {text:'Текст1'},
    {text:'Текст2'},
    {text:'Текст3'},
    {text:'Текст4'},
    {text:'Текст5'}
];

let button = document.querySelector('.button');
let phrase = document.querySelector('.phrase');

button.addEventListener('click', function () {
    for (let count = 0; count < phrases.length; count++) {
        phrase.innerText = phrases[count].text
    }
})
body {
    background-color: rgba(40, 39, 39, 1);
    color: white;
}

.header {
    text-align: center;
    font-size: 25px;
}

.button {
    width: 175px;
    height: 55px;
    position: absolute;
    right: 200px;
    bottom:100px;
    font-size: 25px;
    margin-top: 450px;
    margin-left: 1100px;
    cursor: pointer;
    transition: opacity 0.2s;
    box-sizing: border-box;
    border: 1px solid white;
}

.buttontext {
    position: absolute;
    right: 255px;
    top:290px;
    font-family: Russo One;
    font-size: 25px;
}

.phrase {
  position: absolute;
  left: 30px
}
<!DOCTYPE html>
<html lang="ru">
    <head>
        <script src="js.js"></script>
        <link rel="stylesheet" href="css.css" type="text/css"/>
       <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible">
    <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="keywords" content="Keywords">
        <meta name="description" content="Content">
    </head>
<body>
    <div class="header">
    <h1 class="logo">Logo</h1>
    </div>
    <div class="buttontext">
        Button
    </div>
    <div class="button">
    </div>
    <div class="advice">
        <span class="phrase">
            Место отображения текста
        </span>
    </div>
</body>

</html>

В общем, есть код, есть кнопка, есть массив. Я хочу, чтобы после каждого нажатия отображался один элемент массива (последовательно). У меня получилось сделать последовательное отображение, но оно работает неправильно. Дело в том, что всего лишь при одном нажатии на кнопку поочередно начинают отображаться все элементы массива без остановки (он останавливается только тогда, когда цикл становится более длинным, чем массив (имею ввиду count < phrases.length)). Буду очень благодарен любой помощи! P.S html/css я упростил. У меня на сайте последовательно выводятся все элементы массива по порядку без остановки, но когда я написал код сюда, то тут он работает по другому (выводиться только последнее значение массива). Но, в любом случае, мне нужно, чтобы при каждом нажатии выводилось одно значение массива по порядку. Ещё раз, заранее, огромное спасибо за любую помощь!

1 ответ 1

1

Проблема в том, что вы не сохраняете последний элемент, который был добавлен.

const phrases = [
    {text:'Текст1'},
    {text:'Текст2'},
    {text:'Текст3'},
    {text:'Текст4'},
    {text:'Текст5'}
];

const button = document.querySelector('.button');
const phrase = document.querySelector('.phrase');

let currentActiveIndex = 0;

button.addEventListener('click', function () {
    if (currentActiveIndex < phrases.length) {
      phrase.innerText = phrases[currentActiveIndex].text;
      currentActiveIndex = currentActiveIndex + 1;
    }  
})
body {
    background-color: rgba(40, 39, 39, 1);
    color: white;
}

.header {
    text-align: center;
    font-size: 25px;
}

.button {
    width: 175px;
    height: 55px;
    position: absolute;
    right: 200px;
    bottom:100px;
    font-size: 25px;
    margin-top: 450px;
    margin-left: 1100px;
    cursor: pointer;
    transition: opacity 0.2s;
    box-sizing: border-box;
    border: 1px solid white;
}

.buttontext {
    position: absolute;
    right: 255px;
    top:290px;
    font-family: Russo One;
    font-size: 25px;
}

.phrase {
  position: absolute;
  left: 30px
}
<!DOCTYPE html>
<html lang="ru">
    <head>
        <script src="js.js"></script>
        <link rel="stylesheet" href="css.css" type="text/css"/>
       <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible">
    <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="keywords" content="Keywords">
        <meta name="description" content="Content">
    </head>
<body>
    <div class="header">
    <h1 class="logo">Logo</h1>
    </div>
    <div class="buttontext">
        Button
    </div>
    <div class="button">
    </div>
    <div class="advice">
        <span class="phrase">
            Место отображения текста
        </span>
    </div>
</body>

</html>

1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.