如何在javascript或使用jquery的for循环问题中显示消息
我试了差不多两天但仍然没有。 也许有人可以帮助那些在javascript循环中技术娴熟的人。
我有这个代码:
$(function(){ var len = $('#groupContainer > div').length; var arr = []; for(var i=0; i < len; i++){ var number = $('#number_' + [i + 1]); var date = $('#date_' + [i + 1]); var count = i + 1; var message =""; console.log(number) var a = number.map(function(){ return this.value; }); var b = date.map(function(){ return this.value; }); var newObj = {number: a[0], date: b[0]} arr.push(newObj); } var message = ""; for(var c = 0; c < arr.length; c++) { for(var d in arr[c]) { message += 'Group: ' + [c + 1] + '\n'; if(arr[c].hasOwnProperty(d)) { if(arr[c][d] == "") { message += d + ' is required!\n'; } } message = message + "\n"; } } alert(message); });
和预期的产量:
如果组1中的所有字段都已填充且组2未显示警告框:
Group 2: Number is required! Date is required!
如果所有字段都未填写显示:
Group 1, 2 Number is required! Group 1, 2 Date is required!
如果所有字段都填满了什么都不做
这是我的FIDDLE
您的代码太复杂 ,应该简化。
您需要将消息保存在object
,稍后循环显示它们以按顺序显示消息。
var messages = {}; var message = ""; for(var c = 0; c < arr.length; c++) { var groupMessage = false; for(var d in arr[c]) { if(arr[c].hasOwnProperty(d)) { if(arr[c][d] == "") { if(messages[d]==undefined) { messages[d]={groups:[]}; } messages[d].groups.push(c+1); } } } var lastgroup = ""; for(i in messages) { m = messages[i]; if(m.groups.join(",")==lastgroup) { message = message.replace("Group "+m.groups.join(",")+" ","Group "+m.groups.join(",")+":\n"); message+=i+" is required!\n"; } else { message+="Group "+m.groups.join(",")+" "+i+" is required!\n"; } lastgroup = m.groups.join(","); } // ..... }
$(function(){ var len = $('#groupContainer > div').length; var arr = []; for(var i=0; i < len; i++){ var number = $('#number_' + [i + 1]); var date = $('#date_' + [i + 1]); var count = i + 1; var message =""; var a = number.map(function(){ return this.value; }); var b = date.map(function(){ return this.value; }); var newObj = {number: a[0], date: b[0]} arr.push(newObj); } console.log(arr); var message = ""; for(var c = 0; c < arr.length; c++) { haveErrorInGroup = false; for(var d in arr[c]) { if(arr[c].hasOwnProperty(d)) { if(arr[c][d] == "") { if(!haveErrorInGroup){ haveErrorInGroup= true; message += 'Group: ' + [c + 1] + '\n'; } message += d + ' is required!\n'; } } } } alert(message); });
Number1: Date1: Number2: Date2: