所以我要做的是在每次填写表单并单击相应的按钮时创建一个包含球队信息(名称、联盟、球员)的新对象。
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, []);
})
});}
发布于 2018-12-02 22:09:59
我不确定您希望如何使用存储的团队数据,但有许多方法可以做到这一点。
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']https://stackoverflow.com/questions/53580967
复制相似问题