简体   繁体   中英

How to combine multiple onclick events/elements

I have this toggle function which has multiple buttons.

var button1 = document.querySelector('#button1');
var button2 = document.querySelector('#button2');
var button3 = document.querySelector('#button3');

var toggleState = function (elem, one, two) {
var elem = document.querySelector(elem);
elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one); //ternary operator
};

button1.onclick = function (e) {
toggleState('#div1', 'open', 'closed');
e.preventDefault();
};

button2.onclick = function (e) {
toggleState('#div2', 'open', 'closed');
e.preventDefault();
};

button3.onclick = function (e) {
toggleState('#div3', 'open', 'closed');
e.preventDefault();
};

I've tried querySelectorAll to combine variables but it doesn't work. I think I know why. But I can't figure out a way to write the script more eloquently. (scratch eloquently. respectable is a better word)

How can I combine variables and onclicks so that the code is not so redundant?

Consider a solution similar to the one below. Instead of copying the event handler per element, you could process each of the elements in a loop.

If the element ids are consistent, you could make it even briefer by only specifying the number of toggles and generating the ids on the fly.

var toggles = {
    '#button1': '#div1',
    '#button2': '#div2',
    '#button3': '#div3'
};

Object.keys(toggles).forEach(function(toggle) {
    document.querySelector(toggle).onclick = function (e) {
        toggleState(toggles[toggle], 'open', 'closed');
        e.preventDefault();
    };
});

function toggleState(elem, one, two) {
    var elem = document.querySelector(elem);
    elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one);
};

Here is one solution:

You need to get button elements and trigger an onclick event for them.

Instead of trigger onclick event handler per each button, you could use a loop.

Read more about bind function

var buttons=document.getElementsByTagName('button');
var toggleState = function (elem, one, two) {
    var elem = document.querySelector(elem);
    elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one); //ternary operator
};
for(var i=0;i<buttons.length;i++){
     var button=document.querySelector('#button'+(i+1));
     button.onclick=(function(index){;
        toggleState('#div'+index,'open','closed');
     }).bind(this,i+1);     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM