首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过单击按钮生成包含对象的新var?

如何通过单击按钮生成包含对象的新var?
EN

Stack Overflow用户
提问于 2018-12-02 21:59:35
回答 1查看 33关注 0票数 0

所以我要做的是在每次填写表单并单击相应的按钮时创建一个包含球队信息(名称、联盟、球员)的新对象。

team对象是类team的实例。我目前正在努力将生成的团队存储为变量。

不幸的是,每次单击该按钮时,该变量都会被覆盖。

我该如何解决这个问题?我是否可以在每次点击按钮时创建一个动态变量名(例如,var name = team.name)?我希望每个创建的团队都有一个新的变量,这样我就可以始终识别和访问它。

对不起,我仍然是JS的新手。干杯!:)

代码语言:javascript
复制
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, []); 

    })
});

}

EN

回答 1

Stack Overflow用户

发布于 2018-12-02 22:09:59

我不确定您希望如何使用存储的团队数据,但有许多方法可以做到这一点。

代码语言:javascript
复制
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']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53580967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档