JavaScript 实现数组数据上下页切换

发布时间:2024-08-30 10:20:29    发布者:文昌文城莱奥网络技术工作室    浏览次数:348

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Array Navigation</title>
</head>

<body>
    <div id="currentElement"></div>
    <button id="prevButton">上一个</button>
    <button id="nextButton">下一个</button>

    <script>
        // 定义数组
        const dataArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

        // 获取 DOM 元素
        const currentElement = document.getElementById('currentElement');
        const prevButton = document.getElementById('prevButton');
        const nextButton = document.getElementById('nextButton');

        // 设置初始索引
        let currentIndex = 0;

        // 显示当前元素
        function displayCurrentElement() {
            currentElement.textContent = dataArray[currentIndex];
        }

        // 上一个元素
        function prevElement() {
            console.log('上一个元素');

            currentIndex = (currentIndex - 1 + dataArray.length) % dataArray.length;
            displayCurrentElement();
        }

        // 下一个元素
        function nextElement() {
            console.log('下一个元素');
            currentIndex = (currentIndex + 1) % dataArray.length;
            displayCurrentElement();
        }

        // 初始化显示
        displayCurrentElement();

        // 添加事件监听器
        prevButton.addEventListener('click', prevElement);
        nextButton.addEventListener('click', nextElement);
    </script>
</body>

</html>