所以我想根据数组的元素动态创建一个按钮但是在尝试将参数传递给onclick函数时会遇到错误
function bringforward(maincourse){
var newdiv = document.createElement('div');
newdiv.id="Current class"
newdiv.style="background-color:#207420;height:440px;width:440px";
for(var i = 0;i<maincourse.gradingareas.length; i++){
var gradeplace = document.createElement('p');
gradeplace.id = grades;
newdiv.appendChild(gradeplace);
var button = document.createElement('button');
button.innerHTML = 'Add Grade';
button.onclick = function myfunc(){AddGrade(maincourse.gradingareas[i])};
gradeplace.appendChild(button);
}
AddGrade函数是一个简单的警报,它将推送给定的值
function AddGrade(toadd){
var newgrade=prompt("Please enter a grade scaled up to 100 points","0 - 100");
if (newgrade!=null){
toadd.grades.push(newgrade);
}
}
课程和评分区域“对象”:
function Course(name, gradingareas, finalgrade) {
this.name = name;
this.gradingareas = gradingareas; //array of gradingareas
this.finalgrade = finalgrade;
}
function GradingArea(name, weight, grades){
this.name = name;
this.weight = weight;
this.grades = grades; //array of grades
}
我认为在onClick中包装函数会处理范围问题,但我在Addgrade中遇到错误,说它正在尝试访问未定义变量的字段。谢谢你的帮助