因此,我有不同数量的表单输入,并且根据应用程序在 CMS 中的设置方式,它们可以位于不同的“页面”上(仅在同一文档中显示/隐藏页面)。这意味着它们的 tab-index 不一定遵循 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'));
}
});
关于javascript - 按照 tab-index 的顺序循环 jQuery 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12415722/