我有2个数组:
我正在尝试在DOM中使用每个数组中的每个数组中的1个在单行中打印它们,并根据它们的分数显示颜色。
javascript
(function($){
$(document).ready(function() {
/* ---------------------------------------------- /*
* Contact form ajax
/* ---------------------------------------------- */
$('#contact-form').find('input,textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault();
var submit = $('#contact-form submit');
var ajaxResponse = $('#contact-response');
var name = $('#contact-form [name="name"]').val();
var email = $('#contact-form [name="email"]').val();
var phone = $('#contact-form [name="phone"]').val();
var message = $('#contact-form [name="message"]').val();
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
dataType: 'json',
data: {
name: name,
email: email,
phone: phone,
message: message,
},
cache: false,
beforeSend: function(result) {
submit.empty();
submit.append('<i class="fa fa-cog fa-spin"></i> Wait...');
},
success: function(result) {
if(result.sendstatus == 1) {
ajaxResponse.html(result.message);
$form.fadeOut(500);
} else {
ajaxResponse.html(result.message);
}
}
});
}
});
});
})(jQuery);
我的预期结果应该是:
function paintGrades (gradeArr, coursArr) {
gradeArr.forEach(function (element) {
var gradeColor = 'bad';
if (element.gradeArr >= 80) {
gradeColor = 'good';
} else if (element.gradeArr >= 60) {
gradeColor = 'ok';
} else if (element.gradeArr === 0) {
gradeColor = 'normal';
}
document.getElementById('grade').innerHTML +=
"<div class='" + gradeColor + "'>" + element.coursArr + ": " + element.gradeArr + "</div>" + "<hr>";
})
}
...
答案 0 :(得分:1)
假设数组具有相同的长度(如果不是,则使用错误检查句柄),可以使用一个for
循环遍历两个数组。
function paintGrades (gradeArr, coursArr) {
// check that gradeArr.length === courseArr.length
for(let i=0; i<gradeArr.length; i++){
let grade = gradeArr[i];
let course = coursArr[i];
// do stuff
}