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

260
Visualizações
onclick modifier function referencing variable instead of using variable value (JavaScript)

(Edit: Someone asked for where trueName is defined in relation to the loop, so I included it in the code sample. relPath is defined in the function parameter)

I have a forEach loop that is meant to clone a template and set an onclick function to open a link for each clone. From the code sample below, you can see that I have 2 variables - relPath and trueName - that are supposed to form part of the parameter passed to the function:

function showDirectoryItems(relPath, data){
    Object.keys(data).forEach((item)=>{
        nameSplit = item.split(">>");
        trueName = nameSplit[0];
        ...
        if (data[item]=="file"){
            clone.getElementById("name").onclick = function() {downloadFile(relPath+'/'+trueName)};
        ...

So in theory, one of the clones would have an onclick function of (for example) downloadFile('files/test1.txt'), another would have downloadFile('files/test2.mp3'), etc.

However, when I run the code, the onclick functions in all of the clones seemed to link to the same path of the last item. I checked the code and realised that the onclick functions used variable references instead of an absolute value (i.e., instead of something like 'files'+'/'+'aaa.txt', it was relPath+'/'+trueName):

Image showing the onclick function of an element referencing the relPath and trueName variables instead of an absolute value

As such, how do I set the onclick function to take in the absolute value of these variables during the forEach loop, instead of a variable reference?

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

0

Hey your question may like this:

HTML:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>

JS:

document.querySelectorAll("div").forEach((e) => {
  name123 = e.innerText;
  e.onclick = function () {
    alert(name123);
  };
});

Click any of them will show 9, the last element;

etc

Solution:

Move the [nameSplit, trueName] to onClick scope.

In my example like:

document.querySelectorAll("div").forEach((e) => {
  e.onclick = function () {
   name123 = e.innerText;
   alert(name123);
  };
});

etc

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