按照选项卡索引的顺序循环一个jQuery选择

Loop a jQuery selection in order of tab-index

本文关键字:一个 选择 jQuery 循环 选项 索引 顺序      更新时间:2023-09-26

所以我有不同数量的表单输入,根据应用程序在CMS中的设置方式,它们可以在不同的"页面"上(只需在同一文档中显示/隐藏页面)。这意味着他们的选项卡索引不一定遵循DOM结构。

它们的形式也各不相同。

如何按照选项卡索引的顺序循环(验证)?

(注意:选项卡索引并不总是遵循递增模式,因为其中一个显示/隐藏按钮上的"下一个"按钮也有选项卡索引)

我想过这样的事情:

var $inputs = $('input[type="text"], select, input[type="radio"]'),
numInputs = $inputs.length,
numInputsChecked = 0,
tabIndex = 0;
while(numInputs != numInputsChecked){
  var $input = $inputs.filter(function(){
     return $(this).attr("tabindex") == tabIndex;
  });
  if($input.length){
     // Do validation code
     numInputsChecked++;
  }
  tabIndex++;
}

但我认为应该有更好的方法来完成这项任务。(注意,我还没有真正测试过这段代码,我只是想说明我的想法)

这种方法可以做到,但可能有一种更优雅的方法(我没有花太多时间):

HTML:

<input type="text" tabindex="2" />
<select tabindex="4"></select>
<input type="text" tabindex="1" />
<input type="text" tabindex="3" />

JS:

/**
 * Sort arrays of objects by their property names
 * @param {String} propName
 * @param {Boolean} descending
 */
Array.prototype.sortByObjectProperty = function(propName, descending){
    return this.sort(function(a, b){
        if (typeof b[propName] == 'number' && typeof a[propName] == 'number') {
            return (descending) ? b[propName] - a[propName] : a[propName] - b[propName];
        } else if (typeof b[propName] == 'string' && typeof a[propName] == 'string') {
            return (descending) ? b[propName] > a[propName] : a[propName] > b[propName];
        } else {
            return this;
        }
    });
};
$(function(){
    var elms = [];
    $('input, select').each(function(){
        elms.push({
            elm: $(this),
            tabindex: parseInt($(this).attr('tabindex'))
        })
    });
    elms.sortByObjectProperty('tabindex');
    for (var i = 0; i < elms.length; i++) {
        var $elm = elms[i].elm;
        console.log($elm.attr('tabindex'));
    }
});
jQuery选择器默认按DOM顺序返回一个元素数组。看见http://docs.jquery.com/Release%3AjQuery_1.3.2.

但是,您可以通过扩展jQuery的默认选择器来添加自定义选择器行为,请参阅:http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/,使用类似于此插件的技术对所选输入的数组进行排序。记住忽略那些实际重新排列元素的部分。

如前所述,对对象进行排序是毫无意义的;无论如何,您仍然可以使用Array原型。。。

你的需求值得写那么多代码吗?

你说的"更好的方式"是什么意思?

->选择不那么贪婪的方法(函数调用、缓存对象等)

我认为你的代码是可以的,也许你可以优化你的代码并检查输入:

  var $input = $inputs.filter(function(){
       return $(this).attr("tabindex") == tabIndex;
  });
  // Preventing your code from processing this element upon next loop if any.
  $inputs = $inputs.not($input);

但这在处理hudge节点集合时确实有意义。。。