Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
Why onlick function return this?
let classMessage = document.createElement('class');
document.getElementById("chat").prepend(classMessage);
classMessage.id = tabMsg[0];
classMessage.innerHTML += '<button onclick="del(' + tabMsg[0] + ')">Try it</button>'

function del(parsedata) {
console.log(parsedata)
}

tabMsg is a parsed line (with split).

i dont understand why when i click on the button the output on the console is :

<class id="vuwzbip6dr"><button onclick="del(vuwzbip6dr)">Try it</button><p>gfdgf gdfgf</p></class>

why he dont put the id vuwzbip6dr !!! ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Encapsulating strings with strings within strings generally causes more problems than it solves and therefore should be avoided.

In your case that means this statement:

'<button onclick="del(' + tabMsg[0] + ')">Try it</button>' is causing the issue for you.

That line is interpreted as:

<button onclick="del(v)">Try it</button>

Where v becomes an identifier pointing to the this, or the currentTarget element and not a string like this: "dev('v')".

Looking at the documentation one sees the onclick handler is provided the currentTarget as the first argument to the callback - hence the assignment I mention.

To fix this you should rely on the tools JavaScript provides - namely, it gives you the currentTarget (target element of the click), so all you have to do is use that and ask for it's parent element's id attribute:

classMessage.innerHTML += '<button onclick=del(this)>Try it</button>'

function del(target) {
    console.log(target.parentNode.id)
}

But that isn't recommended either. You should always try to avoid using in-line event handlers. I'll leave that to a different question for you.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda