JavaScript button exclusive thought

Claim:

There are a series of buttons. Each time you click one of them, the button changes its style (take the background color as an example), and the other buttons restore the default style.
Insert picture description here

Realization ideas:

  1. Get all button elements
  2. First remove the background color of other buttons
  3. Set your own style separately

Code:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>按钮1</button>
    <button>按钮2</button>
    <button>按钮3</button>
    <button>按钮4</button>
    <button>按钮5</button>
    <script>
        var btns = document.getElementsByTagName('button');
        // 获取所有按钮元素
        for (var i = 0; i < btns.length; i++) {
     
     
            btns[i].onclick = function() {
     
     
                for (var j = 0; j < btns.length; j++) {
     
     
                    btns[j].style.backgroundColor = '';
                }
                // 先把其他按钮的背景颜色去掉
                this.style.backgroundColor = 'red';
                // 单独设置自己的样式
            }
        }
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109263126