How to find out which of the id’s triggered a javascript function

Asked

Viewed 35 times

2

I am new in the area and would like to know how to identify which of the id’s that triggered the click function. Or if there is a better way to accomplish this code, the idea is to do a javascript quiz.

     <div id="perg1">1: Pergunta 1</div>
     <div id="resp1" onclick="clicar()">1 - resposta 1</div>
     <div id="resp2" onclick="clicar()">2 - resposta 2</div>
     <div id="resp3" onclick="clicar()">3 - resposta 3</div>
     <div id="resp4" onclick="clicar()">4 - resposta 4</div>
     <div id="return" onclick="voltar()">Voltar</div>

2 answers

1

Go to the click() function, and if you are using jquery example,

$(this). val();

Inside the function, place a console.log to verify.

1


One possibility is you pass as a function parameter (inside the onclick) the this which is a reserved word that has the code execution context.

At that moment (inside the onclick) this is the very HTMLElement, namely the div where the onclick was fired.

And within its function clicar you can use this parameter to catch the id. Getting +/- as the example below.

function clicar( el ){
   console.log( el.id );
}
<div id="perg1">1: Pergunta 1</div>
<div id="resp1" onclick="clicar(this)">1 - resposta 1</div>
<!--                             ^ passar `this` como parametro -->
<div id="resp2" onclick="clicar(this)">2 - resposta 2</div>
<div id="resp3" onclick="clicar(this)">3 - resposta 3</div>
<div id="resp4" onclick="clicar(this)">4 - resposta 4</div>
<div id="return" onclick="voltar()">Voltar</div>

  • 1

    Thank you very much! now I will see how I will use the information that is returned to me.

Browser other questions tagged

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