如何使用不同的按钮按下组合更改 HTML 代码

How to alter HTML code with different combinations of button presses

我写了一些由三个按钮和一段组成的代码。 段落说,"Hello my name is Dolly." 按钮让您选择对多莉做三件事之一。你可以打招呼、拥抱或杀死他们,这些按钮分别给出响应。然而,是否可以按下组合按钮以获得不同的响应?例如,如果我按下杀死多莉的按钮,然后按下拥抱多莉的按钮,我可以让它说出拥抱尸体的内容吗?如果可以,怎么做?

当然可以。在 Javascript 中为 dolly 创建一个 variable/array。每次对 dolly 执行操作时,将其添加到此数组中。每次阅读数组并决定你的反应应该是什么。

这可以通过为 dolly 保留一个状态对象来实现。

var dolly = {
  is_alive: true,
  hugCount: 0,
  helloCount: 0,
  message: function() {
    if(!this.is_alive) {
      //whatever you want to print if dolly's dead.
    } 
    if(this.hugCount) {
      //whatever for a certain number of hug counts.
    }        
    if(this.helloCount) {
      //whatever for a certain number of hello counts.
    }

  },
  kill: function(){
    if(this.is_alive){
      this.is_alive = false;
      return this.message();
    }
  }
};

如果这是模拟游戏原型,您可以继续添加更多功能。只是给对象添加更多的功能,如果你需要添加更多的人,比如tina或james,你也可以做一个构造函数。

var Person = function() {
  this.is_alive = true,
  this.hugCount = 0,
  this.helloCount = 0,
};
Person.prototype.message = function() {
    if(!this.is_alive) {
      //whatever you want to print if dolly's dead.
    } 
    if(this.hugCount) {
      //whatever for a certain number of hug counts.
    }        
    if(this.helloCount) {
      //whatever for a certain number of hello counts.
    }

};
Person.prototype.kill = function(){
    if(this.is_alive){
      this.is_alive = false;
      return this.message();
    }
};
Person.prototype.hello = function() {
  this.helloCount+= 1;
  return this.message();
}

现在您可以使用相同的功能生成任意数量的洋娃娃!

var dolly = new Person();
dolly.kill(); //YOU DIED!

编辑 1

根据 Norman Bentley 的建议,您还可以使用数组来跟踪用户与 "dolly" 的交互。

var Person = function() {
  this.is_alive = true,
  this.hugCount = 0,
  this.helloCount = 0,
  this.interaction =  []
};

var ACTIONS = {"HUG":0x01,"KILL":0x02,"GREET":0x03};
// Using hexes in an attempt to save bytes not sure what's the best way to do this!

Person.prototype.interaction = function(action) {
  // you can use an array of constants for your actions.
  this.interaction.push(action);
}

Person.prototype.kill = function() {
 this.interaction(ACTIONS.KILL);
 this.is_alive = false;
 return this.message();
}

编辑 2

要将其与 HTML 一起嵌入,请参阅此 JS fiddle。

https://jsfiddle.net/3jvbqm9a/