[英]each inside each loop in jquery
我有一個表單,其中的字段元素具有諸如required,class1,class2,class3等類。現在,如果以上任何一個類都不滿足,我需要遍歷所有元素並顯示錯誤消息。 我寫了下面的jQuery為必填項。 現在,我還需要層疊其他類。 有人可以指導我嗎?
<input class="required allowalphanum allownospace" type="text" id="first_name" name="first_name" title="First name is required or the data entered was invalid" value=""/>
<input class="required allowalphanum allownospace" type="password" id="password" name="password" title="Password is required or the data entered was invalid" value=""/>
<input class="required confmpasswrd" type="password" id="cnfmPassword" name="cnfmPassword" title="Password needs to match the above field" value=""/>
jQuery的FN
$('#submit_form .required').filter(':visible').each(function () {
var input = $(this);
input.next('ul.errormessages').remove();
input.removeClass('highlight');
if (!input.val()) {
input.addClass('highlight');
var msg = $(this).attr('title');
input.after('<ul class="errormessages"><li>'+msg+'</li></ul>');
returnVal = false;
}
});
現在,我需要首先檢查是否滿足所需的類。 然后,我還需要檢查其他類是否允許字母數字,allownospace,cnfmPassword等。
有人可以指導我嗎?
使用此方法,您可以檢查elem是否具有yourClass:
if ($('elem').hasClass('yourClass')) {
// do stuff
}
使用$ .each,您可以傳入當前索引和元素:
$('selector').each(function(i, e){
if ($(e).hasClass('yourClass')) { // e becomes each elem in the $('selector') object
// do stuff with $(e)
}
})
您可以檢查多個類:
$('selector').each(function(i, e){
if ($(e).hasClass('yourClass') && $(e).hasClass('yourOtherClass') && $(e).hasClass('yourStuffOverHere')) {
// do stuff
}
})
與jQuery的驗證程序插件類似的解決方案:
// List of validating functions for each class
var validators = {
allowalphanum: function(val) {
return /^[a-z0-9]+$/i.test(val);
},
allownospace: function(val) {
return !/\s/.test(val);
}
};
$('#submit_form .required').filter(':visible').each(function () {
var input = $(this);
input.next('ul.errormessages').remove();
input.removeClass('highlight');
if (!input.val()) {
input.addClass('highlight');
var msg = $(this).attr('title');
input.after('<ul class="errormessages"><li>'+msg+'</li></ul>');
returnVal = false;
}
// Get all the classes of the current input
if(this.className) {
var classes = this.className.split(/\s+/);
for(var p in classes) {
if(classes[p] in validators) {
returnVal = returnVal & validators[classes[p]] (input.val());
}
}
}
});
編輯:添加了檢查是否定義了className
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.