我正在尝试使用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
答案 0 :(得分:0)
我使用indexOf(focused)
var focused = document.activeElement;
var nodeList = Array.prototype.slice.call( document.getElementsByClassName('check'));
var txtarea = document.getElementsByClassName("check")[nodeList.indexOf(focused)];
答案 1 :(得分:0)
尝试
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");