繁体   English   中英

我怎样才能只用javascript获取活动类的索引

[英]how can i get the index of active class with only javascript

我正在尝试使用javascript函数获取当前活动元素的索引。

我的HTML是

<input type="text" name="check" class="check"/>
<textarea id="check" class="check"></textarea>

我已经尝试过这样

var focused = document.activeElement;
// I want to insert the index in this to get the selected class
var txtarea = document.getElementsByClassName("check")[1];  

我也试图获得这样的索引

focused.index  && focused.getIndex

我已经使用indexOf(focused)

var focused = document.activeElement;  
    var nodeList = Array.prototype.slice.call( document.getElementsByClassName('check')); 
    var txtarea = document.getElementsByClassName("check")[nodeList.indexOf(focused)];

尝试

window.onload=function() {
  var checks = document.getElementsByClassName("check");
  for (var i=0;i<checks.length;i++) {
    check[i].onfocus=function() {this.className+=" active";)
    check[i].onblur=function() {this.className.replace(" active","");
  }
}

那你可以用

document.querySelector(".active");

如果您想知道活动检查的索引:

window.onload=function() {
  var checks = document.getElementsByClassName("check");
  for (var i=0;i<checks.length;i++) {
    check[i].setAttribute("data-idx")=i;
    check[i].onfocus=function() {this.className+=" active";)
    check[i].onblur=function() {this.className.replace(" active","");
  }
}

document.querySelector(".active").getAttribute("data-idx");

暂无
暂无

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

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