Find out clicked object id

Asked

Viewed 37 times

-2

I am making a mini shop, and my difficulty is to recover the id of the clicked object, so when click on the item, another page with the information of the clicked object is loaded. In the case of the variable to in the open functionItem will receive the id:

    var item = [
        {
            id: '0',
            produto: 'Camisa branca',
            img: 'imagens/camisabranca.jpg',
            quantidade: '0',
            valor: 'R$ 100'  
            
        },

        {
            id: '1',
            produto: 'Camisa preta',
            img: "imagens/camisapreta.jpg",
            quantidade: '0',
            valor: 'R$ 120'
        },

        {
            id: '2',
            produto: 'Camisa azul',
            img: 'imagens/camisaazul.jpg',
            quantidade: '0',
            valor: 'R$ 150'
        },
    ]

    

    inicializarLoja = () => {
      
       var novaDiv = document.createElement('div')
       for(let i = 0; i<item.length; i++)
       
       novaDiv.innerHTML += `
       <a onclick ="abrirItem()" id="" href="produto.html" class="item">
            
            <p class = "titulo">${item[i].produto}</p>
            <img style="width: 100px; height:117px;" src = "${item[i].img}">
            <span> ${item[i].valor} </span>
        </a>
       `
        novaDiv.className = 'nova'
        
        document.body.appendChild(novaDiv)
        console.log(novaDiv.id)
    }

   
    abrirItem = () => {
    window.open =  "produto.html" 
    let a = 0
        
    let novoItem = document.createElement('div')
        
    novoItem.innerHTML = `
       <div >
            
            <p class = "titulo">${item[a].produto}</p>
            <img style="width: 100px; height:117px;" src = "${item[a].img}">
            <span> ${item[a].valor} </span>
        </div>
       `
        novoItem.className = 'novo'
        document.body.appendChild(novoItem)

    }

1 answer

0

Simply pass an element reference as a parameter using the this. A simplified example of the use is the following:

const clicar = (id) => {
  console.log(`Elemento ${id} foi clicado`);
};
<button id="botao1" onclick="clicar(this.id)">Teste</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.