Как открыть эквивалентный номер массива на другом массиве?
Прежде всего, я прошу прощения за этот заголовок. Может быть, это не лучшее, чтобы объяснить мою проблему. Кроме того, я пытался просмотреть предложенные сообщения, но я не мог их точно понять.
Я пытаюсь получить следующее.
Массив с элементами из DOM, который дает:
var boxes = ["box1", "box2", "box3"]
А также массив с всплывающим окном, с отображением: нет
var popups = ["pop1", "pop2", "pop3"]
Я хочу, чтобы при нажатии на поля [i] открывались всплывающие окна [i].
Поэтому мой вопрос здесь заключается в том, как сохранить это событие, которое дает мне [i], чтобы я мог открыть точно такое же [i] во всплывающих окнах.
Извините, что не использовал код, но я подумал, что это будет сложнее. Тем не менее, не стесняйтесь построить это с этим:
var boxes = document.getElementsByClassName("box");
var popupss = document.getElementsByClassName("pop");
.wrapper {
display: flex;
justify-content:space-between;
}
.box {
cursor:pointer;
display:flex;
justify-content:center;
align-items:center;
background-color: #FC543A;
padding: 50px;
border-radius: 3px;
}
.wrapper2 {
display:flex;
justify-content:center;
background-color: rgba(0,0,0,0.4);
position:fixed;
height:100%;
width:100%;
z-index:2;
overflow:auto;
}
.pop {
margin-top:6em;
background-color:white;
height: 50px;
width: 80%;
display:none;
justify-content:center;
align-items:center;
}
.hide {
display:none;
}
.show {
display:flex;
}
<div class="wrapper">
<div id="box1" class="box">Box1</div>
<div id="box2" class="box">Box2</div>
<div id="box3" class="box">Box3</div>
</div>
<div class="wrapper2">
<div class="pop" id="pop1">
Pop1!
</div>
<div class="pop" id="pop2">
Pop2!
</div>
<div class="pop" id="pop3">
Pop3!
</div>
</div>
Спасибо!
3 ответа
Вы действительно не принимаете лучший подход здесь. Всякий раз, когда вы обнаружите, что дублируете код, остановитесь и переведите дыхание. Нет необходимости создавать 3 поп-секции HTML. У вас должен быть только один HTML-заполнитель для вашего всплывающего сообщения и сохранить возможные значения для этого сообщения в массиве JavaScript. Это делает HTML чище и избавляет от необходимости .hide
CSS класс.
Затем вы просто назначаете каждому полю функцию события щелчка, которая устанавливает соответствующее всплывающее сообщение (из массива) в заполнитель всплывающего окна.
// Store possible pop messages:
var popMessages = ["Pop1!", "Pop2!", "Pop3!"];
// Get reference to pop placeholder
var pop = document.getElementById("pop");
// Use .querySelectorAll() instead of .getElementsByClassName
// since the latter doesn't perform as well due to returning
// a "live" node list. Also, convert the returned node list
// into a proper array, so that .forEach() can be used on it.
var boxes = Array.prototype.slice.call(document.querySelectorAll(".box"));
// Loop over the boxes
boxes.forEach(function(box, index){
// Set each box to have a click event handling function
box.addEventListener("click", function(){
// Use the pop message corresponding to the index of the box being clicked.
pop.textContent = popMessages[index];
});
});
.wrapper {
display: flex;
justify-content:space-between;
}
.box {
cursor:pointer;
display:flex;
justify-content:center;
align-items:center;
background-color: #FC543A;
padding: 50px;
border-radius: 3px;
}
.wrapper2 {
display:flex;
justify-content:center;
background-color: rgba(0,0,0,0.4);
position:fixed;
height:100%;
width:100%;
z-index:2;
overflow:auto;
}
.show {
display:flex;
}
<div class="wrapper">
<div id="box1" class="box">Box1</div>
<div id="box2" class="box">Box2</div>
<div id="box3" class="box">Box3</div>
</div>
<div class="wrapper2">
<div class="pop" id="pop"></div>
</div>
Следующее (сильно прокомментированное) делает ваш трюк. Фрагмент стека скрывает результаты, поэтому разверните их на всю страницу.
Используемые функции JavaScript:
//select all divs with class box and iterate them
Array.prototype.forEach.call(document.querySelectorAll("div.box"), function(element, index) {
//we use Array.prototype.map and use call to pass the node list into the map function to iterate
//assign click handlers
//when an element is clicked it will fire the function boxHandler. We use bind to pass the index of the element to the function.
element.addEventListener("click", boxHandler.bind(element, index), true);
//hide all pops
document.querySelectorAll("div.pop")[index].classList.add("hide");
});
function boxHandler(index) {
//select the div based upon the index.
var pop = document.querySelectorAll("div.pop")[index];
if (pop.getAttribute("data-clicked") != 1) {
//add show to class using classlist.add
pop.classList.add("show");
pop.classList.remove("hide");
pop.setAttribute("data-clicked", 1);
} else {
pop.classList.remove("show");
pop.classList.add("hide");
pop.setAttribute("data-clicked", 0);
}
}
.wrapper {
display: flex;
justify-content: space-between;
}
.box {
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
background-color: #FC543A;
padding: 50px;
border-radius: 3px;
}
.wrapper2 {
display: flex;
justify-content: center;
background-color: rgba(0, 0, 0, 0.4);
position: fixed;
height: 100%;
width: 100%;
z-index: 2;
overflow: auto;
}
.pop {
margin-top: 6em;
background-color: white;
height: 50px;
width: 80%;
display: none;
justify-content: center;
align-items: center;
}
.hide {
display: none;
}
.show {
display: flex;
}
<div class="wrapper">
<div id="box1" class="box">Box1</div>
<div id="box2" class="box">Box2</div>
<div id="box3" class="box">Box3</div>
</div>
<div class="wrapper2">
<div class="pop" id="pop1">
Pop1!
</div>
<div class="pop" id="pop2">
Pop2!
</div>
<div class="pop" id="pop3">
Pop3!
</div>
</div>
Попробуйте что-то вроде этого:
const boxes = document.querySelectorAll('.box')
const popups = document.querySelectorAll('.pop')
const doSthAbPopup = popupIndex => {
// Replace this with whatever you want to do with the popups
console.log(popups[popupIndex].textContent)
}
[...boxes].forEach((box, index) => {
box.addEventListener('click', () => {
doSthAbPopup(index)
})
})
Вы можете добавить несколько проверок, чтобы убедиться, что у вас одинаковое количество ящиков и всплывающих окон.
forEach
хорошо для этого, так как обеспечивает закрытие index
,