所以我想做的是每次填写表格并单击相应按钮时创建一个包含团队信息(名称,联赛,球员)的新对象。
team对象是类team的实例。我目前正在努力将生成的团队存储为变量。
不幸的是,每次单击按钮时都会覆盖该变量。
我该如何解决?我是否可以在每次单击按钮时以某种方式创建一个动态变量名(例如var name = team.name)?我想要为创建的每个团队都使用一个新变量,以便始终可以识别和访问它。
对不起,我还是JS的新手。干杯! :)
class team {
constructor(teamname, teamleague, players) {
this.teamname = teamname;
this.teamleague = teamleague;
this.players = [];
}
var generatedTeamName = "";
var generatedTeamLeague = "";
var newteam = "";
var listofTeams =[];
$(document).ready(function(){
/* --- NEW TEAM ----------------------------------------------------------------------------------------------------*/
$("#generateteam").click(function(){
generatedTeamName = $('input[name="text-5"]').val();
generatedTeamLeague = $('input[name="text-6"]').val();
var storenewTeamhere = new team (generatedTeamName, generatedTeamLeague, []);
})
});
}
答案 0 :(得分:0)
我不确定您要如何使用已存储的团队数据,但是有很多方法可以执行此操作。
class Team {
constructor(teamname, teamleague, players) {
this.teamname = teamname;
this.teamleague = teamleague;
this.players = players;
}
}
/* the array method */
const listOfTeams = [];
$("#generateteam").click(function () {
let name = $('input[name="text-5"]').val();
let league = $('input[name="text-6"]').val();
let team = new Team(
name,
league,
[]
);
listOfTeams.push(team);
// you can access the team as simply `team` here
});
// here you can access the teams by array index
// listOfTeams[i]
/* the object method */
const teams = {};
$("#generateteam").click(function () {
let name = $('input[name="text-5"]').val();
let league = $('input[name="text-6"]').val();
let team = new Team(
name,
league,
[]
);
teams[name] = team;
// you can access the team as simply `team` here
});
// you can now access the team by teamname
// teams['Some Team Name']