The thought of JavaScript button exclusivity

Time:2021-1-13

requirement:

There are a series of buttons. Each time you click one of them, the button will change the style (take the background color as an example), and the other buttons will return to the default style.

Realization idea:

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

Code implementation:

Show onlyContent in label

Button 1
    Button 2
    Button 3
    Button 4
    Button 5
    
        var btns = document.getElementsByTagName('button');
        //Get all button elements
        for (var i = 0; i < btns.length; i++) {
            btns[i].onclick = function() {
                for (var j = 0; j < btns.length; j++) {
                    btns[j].style.backgroundColor = '';
                }
                //Remove the background color of other buttons first
                this.style.backgroundColor = 'red';
                //Set your own style individually
            }
        }