2
I’m trying to add an eventListener, click-type, to my Ivs through their classes, which are called: option-title. However as it is more than one title, I would like you to recover exactly the one I am clicking.
Follows the code:
var groupOptions = document.getElementsByClassName("option-title");
for(var i = 0; i < groupOptions.length; i++){
groupOptions[i].addEventListener("click", message(i));
}
function message(i){
if(i == 1){
alert("Clicado 1!");
}
else if(i == 2 ){
alert ("Clicado 2");
}else if(i == 3){
alert("Clicado 3");
}else if(i == 4){
alert("Clicado 4");
}
}
<div class="box-option option-title">
<span>Title 1</span>
</div>
<div class="box-option option-title">
<span>Title 2</span>
</div>
<div class="box-option option-title">
<span>Title 3</span>
</div>
<div class="box-option option-title">
<span>Title 4</span>
</div>
What I would like to happen is that I click, for example, on the third div, it suits me his index (2). Another question is also whether I can pass some parameter when adding Eventlistener, because I tried to pass the index. Grateful.
Interestingly, Dotevotemedown said that doing this is not right. On the other hand, it helped me do exactly what I needed to do.
– Wesley Redfield
@Wesleyredfield there are different ways to do it. He probably had another one in mind, maybe like I did here: http://answall.com/a/23788/129 look at example 3.
– Sergio
@Wesleyredfield I expressed myself wrong saying that
não estava correta
, But then I said exactly what Sergio did, that this way would be recording the return of the function. What Sergio did was cool, passing another function as return. It’s just that I’m not used to doing it that way, but it works really well too.– DontVoteMeDown
@Dontvotemedown but it was of great help to know about the "data-Indice". It is that in what I was looking for the solution of Sergio was more quiet to put. Grateful
– Wesley Redfield