所以我有不同数量的表单输入,根据应用程序在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++;
}但我相信应该有更好的方法来完成这项任务。(注意,我并没有实际测试过这段代码,我只是想说明一下我的想法)
发布于 2012-09-14 06:56:23
这种方法可以做到这一点,但可能有一种更优雅的方法(我没有在这方面花太多时间):
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-14 06:50:04
默认情况下,jQuery选择器以DOM顺序返回一个元素数组。参见http://docs.jquery.com/Release%3AjQuery_1.3.2。
但是,您可以通过扩展jQuery的默认选择器来添加自定义选择器行为,请参见:http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/,使用类似于this plugin的技术对所选输入数组进行排序。记住忽略实际重新排列元素的部分。
发布于 2012-09-14 07:37:52
如上所述,对对象进行排序是没有意义的;无论如何,您仍然可以使用Array prototype。..。
你的需求值得写那么多代码吗?
你说的“更好的方式”是什么意思?
->选择不那么贪婪的方法(函数调用、缓存对象等)。
我认为你的代码是好的,也许你可以优化你的代码,并得到检查的输入:
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节点集合时确实很有意义……
https://stackoverflow.com/questions/12415722
复制相似问题