2

所以我有不同数量的表单输入,并且根据应用程序在 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++;
}

但我相信应该有更好的方法来完成这项任务。(注意,我没有实际测试过这段代码,我只是想说明我在想什么)

4

3 回答 3

1

This approach will do it, but there may be a more elegant way (I didn't put much time into this):

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'));
    }
});
于 2012-09-13T22:56:22.693 回答
1

默认情况下,jQuery 选择器按 DOM 顺序返回一个元素数组。请参阅http://docs.jquery.com/Release%3AjQuery_1.3.2

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

于 2012-09-13T22:50:03.500 回答
0

如前所述,对对象进行排序是毫无意义的;无论如何,您仍然可以使用 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);

但这在处理大量节点集合时确实很有意义......

于 2012-09-13T23:37:52.427 回答