I am creating this in plain vanilla JavaScript.
I am trying to load modals by looping over a collection and I am only getting the last modal.
When I do it this way everything is fine.
buttons[0].onclick = function() {modals[0].style.display = "block";return false;}
buttons[1].onclick = function() {modals[1].style.display = "block";return false;}
buttons[2].onclick = function() {modals[2].style.display = "block";return false;}
When I do it this way I only get the last modal no matter which button I click
var i = 0;
while (i < buttons.length) {
buttons[i].onclick = function() {modals[i].style.display = "block";return false;}
i++;
}
Any suggestions?
Event delegation may be a solution for this kind of problems:
document.addEventListener(`click`, handle); function handle(evt) { if (evt.target.dataset.modal) { document.querySelectorAll(`[data-modaldiv]`) .forEach(m => m.classList.remove(`active`)); const divId = evt.target.dataset.modal document.querySelector(`[data-modaldiv='${divId}']`) .classList.add(`active`); } }
[data-modaldiv] { display: none; } [data-modaldiv].active { display: block; }
<button data-modal="1">button 1</button> <button data-modal="2">button 2</button> <button data-modal="3">button 3</button> <p data-modaldiv="1">Modal 1</p> <p data-modaldiv="2">Modal 2</p> <p data-modaldiv="3">Modal 3</p>
It does seem to be the infamous look issue. This is what I came up with.
for (var i = 0, link; i < buttons.length; i++) {
buttons[i].onclick = function(num) {
return function() {
modals[num].style.display = "block";
return false;
};
}(i);
}
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.