如何获取具有属性tabindex的下一个元素

时间:2016-06-21 12:42:57

标签: javascript jquery html5

我希望将下一个元素的tabindex值分配给它的前一个元素,当我尝试运行此代码时,变量el未定义。

if(event.keyCode == 9){
    $(this).removeAttr('readonly');
    var el = $(this).closest('input, select').attr('tabindex');
    var tV = el.val();
    if(el != ' ' || el != null){
        $(this).attr('tabindex', tV - 1);
    }
    else{

    }
}

2 个答案:

答案 0 :(得分:2)

您正在选择下一个输入/选择元素并获取其tabindex。如果没有定义tabindex,则会获得undefined

试试这个:

$(this).nextAll("[tabindex]:first").attr('tabindex');

答案 1 :(得分:2)

这是使用document.querySelector() API的非常基本的选择器逻辑。假设我们有mainElement,我们希望获得mainElement下的tabindex = -1属性和值的下一个元素。

让我们看看;

var   mainElement = document.querySelector('#main'),
inputWithTabIndex = mainElement.querySelector('[tabindex = "-1"]');
console.log(inputWithTabIndex);
setTimeout(function() {
             inputWithTabIndex.setAttribute("tabindex","0");
             console.log(inputWithTabIndex);
           },1000);
<div id="main">
  <div class="inputContainer">
    <input type="text" placeholder="Type here">
  </div>
  <div class="inputContainer">
    <input type="text" placeholder="Type here">
  </div>
  <div class="inputContainer">
    <input type="text" placeholder="Type here" tabindex = "-1">
  </div>
  <div class="inputContainer">
    <input type="text" placeholder="Type here">
  </div>
</div>