简体   繁体   English

计算班级在特定事件发生之前出现了多少次

[英]Count how many times a class has appeared before a specific occurance

In my code, when you click on one of the numbered Divs, it will alert the name of the class attached to the div. 在我的代码中,当您单击编号的Divs之一时,它会警告附加到div的类的名称。 What I'm unsure of is how can I detect the number of previous occurrences of that class, so that, for example, if I clicked 2 it will alert myClass(1) to say it's the second occurrence of it? 我不确定的是如何检测该类先前出现的次数,例如,如果单击2 ,它将提醒myClass(1)说这是该类的第二次出现? (assuming 0 would be the first?) (假设第一个为0 ?)

In need of plain vanilla Javascript for this one. 这个需要普通的Javascript。

 function counter(itemClicked) { var theClass = itemClicked.className; alert(theClass); } 
 <div class="myClass" onclick="counter(this)">1</div> <div class="myClass" onclick="counter(this)">2</div> <div class="myClass" onclick="counter(this)">3</div> 

As written by Ryan, this is a highly insecure scenario which will break should the element have multiple classes (and possibly for other things too), however, for your example a simple indexOf will work: 正如Ryan所写的那样,这是一个非常不安全的方案,如果元素具有多个类(并且可能还有其他用途),则该方案会中断,但是,对于您的示例,简单的indexOf可以工作:

 function counter(el) { let index = Array.from(document.getElementsByClassName(el.className)).indexOf(el); alert(++index); } 
 <div class="myClass" onclick="counter(this)">1</div> <div class="myClass" onclick="counter(this)">2</div> <div class="myClass" onclick="counter(this)">3</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM