I see no reason to use an array at all.
Here is my implementation example:
$('.tabs-block .tab-link').on('click', function() { if (!$(this).hasClass('active')) { var parentTabs = $(this).closest('.tabs-block'); parentTabs.find('.tab-link.active, .tab-content.active').removeClass('active'); var elemIndex = $(this).index(); $(this).addClass('active'); parentTabs.find('.tab-content').eq(elemIndex).addClass('active'); } });
body {background: #333;} .tabs-block { display: block; width: 100%; border-radius: 3px; overflow: hidden; } .tab-link-block { display: block; width: 100%; background: #4184f3; overflow: hidden; } .tab-link { padding: 0 10px; height: 50px; line-height: 50px; color: #bbb; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; cursor: pointer; } .tab-link:not(.active):hover { background: rgba(255, 255, 255, .1); } .tab-link.active { background: rgba(255, 255, 255, .1); color: #fff; } .tab-content-block { display: block; width: calc(100% - 20px); min-height: calc(50px - 20px); padding: 10px; background: #fefefe; color: #333; } .tab-content:not(.active) { display: none; } /* horizontal */ .tabs-block:not(.-vertical) .tab-link-block { height: 50px; } .tabs-block:not(.-vertical) .tab-link-block::after { content: ''; display: block; clear: both; } .tabs-block:not(.-vertical) .tab-link { display: inline-block; float: left; min-width: calc(50px - 20px); max-width: calc(150px - 20px); margin-right: 2px; } .tabs-block:not(.-vertical) .tab-link.active { box-shadow: 0 -3px 0 0 #f4b142 inset; } .tabs-block:not(.-vertical) .tab-link:last-child { margin-right: 0; } /* horizontal */ /* vertical */ .tabs-block.-vertical { display: grid; grid-template-columns: 150px 1fr; grid-gap: 0; } .tabs-block.-vertical .tab-link { display: block; width: calc(100% - 20px); } .tabs-block.-vertical .tab-link.active { box-shadow: -3px 0 0 0 #f4b142 inset; } /* vertical */ .tab-link { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; transition: all linear .2s; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="tabs-block"> <div class="tab-link-block"> <div class="tab-link active">Первая вкладка</div> <div class="tab-link">Вторая вкладка</div> <div class="tab-link">Третья вкладка</div> </div> <div class="tab-content-block"> <div class="tab-content active">1</div> <div class="tab-content">2</div> <div class="tab-content">3</div> </div> </div> <br><br> <div class="tabs-block -vertical"> <div class="tab-link-block"> <div class="tab-link active">Первая вкладка</div> <div class="tab-link">Вторая вкладка</div> <div class="tab-link">Третья вкладка</div> </div> <div class="tab-content-block"> <div class="tab-content active">1</div> <div class="tab-content">2</div> <div class="tab-content">3</div> </div> </div>
.sectioncan be different. Better for each.sectionto do a data-attribute. In addition, it is bad to attach an event throughonclick. Better throughaddEventListener. - Stepan Kasyanenko