<button data-block="block-one">69</button>
<button data-block="block-two">187</button>
<button data-block="block-three">666</button>
<div class="block block-one">hello, world!!</div>
<div class="block block-two">fuck the world</div>
<div class="block block-three">fuck everything</div>
$('body').on('click', 'button', function() {
const $block = $(`.${this.dataset.block}`).toggleClass('show');
$('.block').not($block).removeClass('show');
});
// или
document.addEventListener('click', ({ target: { dataset: { block } } }) => {
if (block) {
document.querySelectorAll('.block').forEach(({ classList: cl }) => {
cl[cl.contains(block) ? 'toggle' : 'remove']('show');
});
}
});
или
<button class="button">69</button>
<button class="button">187</button>
<button class="button">666</button>
<div class="block block-one">hello, world!!</div>
<div class="block block-two">fuck the world</div>
<div class="block block-three">fuck everything</div>
const $blocks = $('.block');
const $buttons = $('.button').click(function() {
const $block = $blocks.eq($buttons.index(this)).toggleClass('show');
$blocks.not($block).removeClass('show');
});
// или
const blocks = document.querySelectorAll('.block');
const buttons = document.querySelectorAll('.button');
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick() {
const index = Array.prototype.indexOf.call(buttons, this);
blocks.forEach((n, i) => n.classList[i === index ? 'toggle' : 'remove']('show'));
}