How do I make it open a "modal window" with information about the product when I click on the card.
<div class="card"> <div class="imgBox"> <img src="./img/bau.png" alt="Produto" class="mouse"> </div> <div class="contentBox"> <h3>Plugin</h3> <h2 class="price">25.<small>00</small> BRL</h2> <a href="#" class="buy">Comprar Agora!</a> </div> </div>
There are several methods. There’s no real right or wrong here either. The method must be suitable for your application. There's nothing fundamentally wrong if you always try to keep your methods somewhat abstract.
In the example below, I've used the link modal example below your question and made the following adjustments.
Added a data object in which I manage the corresponding content of the modal. Here, you can also use API calls against the interface.
I assigned an EventListener to all buttons.
The variable parts in the modal are exchanged with the corresponding content when clicked.
Finish!
const modalData = [ {id: 1, title: "标题一", content: "bla"}, {id: 2, title: "标题二", content: "bla blu"}, ]; // 获取模态框 var modal = document.getElementById("myModal"); // 获取打开模态框的按钮 var btns = document.querySelectorAll(".myBtn"); // 获取关闭模态框的元素 var span = document.getElementsByClassName("close")[0]; // 当用户点击按钮时,打开模态框 btns.forEach(b => { b.addEventListener('click', (e) => { modal.style.display = "block"; const dataId = e.target.getAttribute("data-id") const data = modalData.filter(m => m.id == dataId); const modalTitle = document.querySelector("#myModal .title"); const modalContent = document.querySelector("#myModal .content"); modalTitle.innerHTML = data[0].title; modalContent.innerHTML = data[0].content; }) }); // 当用户点击 (x)时,关闭模态框 span.onclick = function() { modal.style.display = "none"; } // 当用户点击模态框之外的任何地方时,关闭模态框 window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }