Есть ли способ упростить этот код? Я просто нахожу это слишком длинным для простой функции.
Я пытался использовать querySelectorAll(), но мне было трудно перекодировать его.
Пожалуйста, смотрите включенный фрагмент.
Пытался найти более простой способ, к сожалению не нашел.
function myFunction() {
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (moreText.style.display === "none") {
moreText.style.display = "inline";
document.getElementById("more2").style.display = 'none';
document.getElementById("myBtn").style.backgroundColor = "#000000";
document.getElementById("myBtn2").style.backgroundColor = "#006668";
} else {
moreText.style.display = "inline";
document.getElementById("more2").style.display = 'none';
document.getElementById("myBtn").style.backgroundColor = "#000000";
document.getElementById("myBtn2").style.backgroundColor = "#006668";
} }
function myFunction2() {
var moreText = document.getElementById("more2");
var btnText = document.getElementById("myBtn2");
if (moreText.style.display === "none") {
moreText.style.display = "inline";
document.getElementById("more").style.display = 'none';
document.getElementById("myBtn").style.backgroundColor = "#006668";
document.getElementById("myBtn2").style.backgroundColor = "#000000";
} else {
moreText.style.display = "inline";
document.getElementById("more").style.display = 'none';
document.getElementById("myBtn").style.backgroundColor = "#006668";
document.getElementById("myBtn2").style.backgroundColor = "#000000";
} }
function myFunction3() {
var moreText = document.getElementById("more3");
var btnText = document.getElementById("myBtn3");
if (moreText.style.display === "none") {
moreText.style.display = "inline";
document.getElementById("more").style.display = 'none';
document.getElementById("more2").style.display = 'none';
document.getElementById("myBtn").style.backgroundColor = "#006668";
document.getElementById("myBtn2").style.backgroundColor = "#006668";
} else {
moreText.style.display = "inline";
document.getElementById("more").style.display = 'none';
document.getElementById("more2").style.display = 'none';
document.getElementById("myBtn").style.backgroundColor = "#006668";
document.getElementById("myBtn2").style.backgroundColor = "#006668";
} } div.scrollmenu {
background-color: #006668;
overflow: auto;
white-space: nowrap;
}
#more {display: none;}
#more2 {display: none;}<div class = "scrollmenu">
<a onclick = "myFunction()" id = "myBtn" href = "#Event1">Event 1</a>
<a onclick = "myFunction2()" id = "myBtn2" href = "#Event2">Event 2</a>
</div>
<span id = "more">Display Event Here 1.</span>
<span id = "more2">Display Event Here 2.</span>





Смотрите мои комментарии в обновленном примере ниже.
При щелчке мы удаляем ВСЕ активные классы на кнопках и в текстовых областях, а затем добавляем активный класс к тем, которые в нем нуждаются.
Преимущество здесь в том, что вы не сохраняете активный класс в javascript. Таким образом, вы не рискуете, что представление и сохраненное состояние могут быть рассинхронизированы другими сценариями, которые могут быть запущены.
// first we get all the buttons and text areas
var btns = document.querySelectorAll('.btn');
var mores = document.querySelectorAll('.more');
// we add an event listener by looping trough all the buttons
for (const btn of btns) {
btn.addEventListener('click', handleClick);
}
// handle the button click
function handleClick(event){
event.preventDefault();
// remove the active class on ALL the buttons
for (const btn of btns) {
btn.classList.remove('active');
}
// add the active class on the clicked button
event.target.classList.add('active');
//remove the active class on all the text areas
for (const more of mores) {
more.classList.remove('active');
}
// here we get the data-show attribute of the clicked element
// and use it to show the right text area
document.querySelector(`#${event.target.dataset.show}`).classList.add('active');
}div.scrollmenu {
background-color: #006668;
overflow: auto;
white-space: nowrap;
}
.btn.active{
background: #000000;
}
.more{
display: none;
}
.more.active{
display: block;
}<div class = "scrollmenu">
<a class = "btn" href = "#" data-show = "more1" >Event 1</a>
<a class = "btn" href = "#" data-show = "more2">Event 2</a>
</div>
<span id = "more1" class = "more">Display Event Here 1.</span>
<span id = "more2" class = "more">Display Event Here 2.</span>.px-0 {
padding-left: 0 !important;
padding-right: 0 !important;
}
ul.nav.nav-tabs {
background-color: #006668;
}
ul.nav.nav-tabs li a,ul.nav.nav-tabs li a:hover {
color: #fff;
border: 0;
background-color: transparent;
}
ul.nav.nav-tabs li.active a,ul.nav.nav-tabs li.active a:hover {
background-color: #000;
border: 0;
border-radius: 0;
color: #fff;
}
.tab-content {
padding: 20px;
}<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class = "container-fluid px-0">
<ul class = "nav nav-tabs">
<li class = "active"><a data-toggle = "tab" href = "#home">Event 1</a></li>
<li><a data-toggle = "tab" href = "#menu1">Event 2</a></li>
<li><a data-toggle = "tab" href = "#menu2">Event 3</a></li>
<li><a data-toggle = "tab" href = "#menu3">Event 4</a></li>
</ul>
<div class = "tab-content">
<div id = "home" class = "tab-pane fade in active">
<p>Display Event Here 1.</p>
</div>
<div id = "menu1" class = "tab-pane fade">
<p>Display Event Here 2.</p>
</div>
<div id = "menu2" class = "tab-pane fade">
<p>Display Event Here 3.</p>
</div>
<div id = "menu3" class = "tab-pane fade">
<p>Display Event Here 4.</p>
</div>
</div>
</div>Уверен, что вопрос включает в себя отображение/скрытие контента. Включение всей библиотеки bootstrap css, полной библиотеки jquery и bootstrap JS (всего более 60 КБ) может быть немного излишним для того, чего мы пытаемся достичь здесь.
На самом деле я планировал включить эту анимацию после того, как упростил код, спасибо за ее включение.
Вы можете сделать что-то вроде этого:
const myBtns = document.querySelectorAll(".myBtn");
const descriptions = document.querySelectorAll(".description");
function myFunction(e) {
myBtns.forEach( btn => {
btn.classList.remove("active");
});
descriptions.forEach( description => {
description.classList.remove("show");
});
e.target.classList.add("active");
document.querySelector("."+e.target.getAttribute("data-show")).classList.add("show");
}div.scrollmenu {
background-color: orange;
}
.hide {
display: none;
}
.show {
display: block;
}
.active {
background-color: green;
}<div class = "scrollmenu">
<a onclick = "myFunction(event)" class = "myBtn" href = "#Event1" data-show = "more">Event 1</a>
<a onclick = "myFunction(event)" class = "myBtn" href = "#Event2" data-show = "more2">Event 2</a>
</div>
<span class = "hide description more">Display Event Here 1.</span>
<span class = "hide description more2">Display Event Here 2.</span>Привет, сэр, я думаю, что это делает это. Спасибо!
Используя ниже javascript вы можете сделать это проще
function myFunction(event) {
var href = event.target.href.substring(event.target.href.indexOf('#') + 1);
var id = event.target.id;
var x = document.getElementsByTagName("span");
var y = document.getElementsByTagName("a");
var i,j;
for (i = 0; i < x.length; i++) {
x[i].style.display = 'none';
}
for (j = 0; j < y.length; j++) {
y[j].style.backgroundColor = "#006668";
}
document.getElementById(href).style.display = 'inline';
document.getElementById(id).style.backgroundColor = "#000000";
}div.scrollmenu {
background-color: #006668;
overflow: auto;
white-space: nowrap;
}
span {display: none;}<div class = "scrollmenu">
<a onclick = "myFunction(event)" id = "myBtn" href = "#Event1">Event 1</a>
<a onclick = "myFunction(event)" id = "myBtn2" href = "#Event2">Event 2</a>
<a onclick = "myFunction(event)" id = "myBtn3" href = "#Event3">Event 3</a>
<a onclick = "myFunction(event)" id = "myBtn4" href = "#Event4">Event 4</a>
<a onclick = "myFunction(event)" id = "myBtn5" href = "#Event5">Event 5</a>
<a onclick = "myFunction(event)" id = "myBtn6" href = "#Event6">Event 6</a>
<a onclick = "myFunction(event)" id = "myBtn7" href = "#Event7">Event 7</a>
<a onclick = "myFunction(event)" id = "myBtn8" href = "#Event8">Event 8</a>
<a onclick = "myFunction(event)" id = "myBtn9" href = "#Event9">Event 9</a>
<a onclick = "myFunction(event)" id = "myBtn10" href = "#Event10">Event 10</a>
</div>
<span id = "Event1">Display Event Here 1.</span>
<span id = "Event2">Display Event Here 2.</span>
<span id = "Event3">Display Event Here 3.</span>
<span id = "Event4">Display Event Here 4.</span>
<span id = "Event5">Display Event Here 5.</span>
<span id = "Event6">Display Event Here 6.</span>
<span id = "Event7">Display Event Here 7.</span>
<span id = "Event8">Display Event Here 8.</span>
<span id = "Event9">Display Event Here 9.</span>
<span id = "Event10">Display Event Here 10.</span>Привет, сэр, не могли бы вы уточнить эту строку для меня? document.getElementById(id).style.backgroundColor = "#000000"; Я беспокоюсь, что это может повлиять на другие идентификаторы на странице, поправьте меня, если я ошибаюсь, сэр.
@pjustindaryll нет, это не повлияет, мы взяли переменную var id = event.target.id; вместо этого вы можете изменить имя переменной на что угодно
Спасибо! Я думаю, теперь я знаю, где я пропустил, я попытался перекодировать это так, document.querySelectorAll("btn","btn1","btn2".....), потому что я пытался исключить один идентификатор.