2016-04-26 33 views
0

我寫了一些由三個按鈕和一個段落組成的代碼。 該段說:「你好我的名字是多莉。」按鈕讓您可以選擇爲Dolly做三件事之一。你可以打個招呼,擁抱或者殺死他們,這些按鈕分別給出迴應。但是,是否可以按下不同響應的按鈕組合?例如,如果我按下按鈕殺死多莉,那麼按下多莉的按鈕,我能否說出一些關於擁抱屍體的事情?如果是這樣,怎麼樣?如何用不同的按鈕組合來更改HTML代碼

+1

通過保持變量爲小車的狀態。 –

+2

請將您的代碼顯示出來,以便處理您的問題 –

+0

@Chewynugget您是否從中受益? –

回答

2

這可以通過保持小車的狀態對象來實現。

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(); 
    } 
    } 
}; 

如果這是一個模擬遊戲原型,您可以繼續添加更多的功能。只需要添加更多的功能到對象,如果你需要添加更多的人像蒂娜或詹姆斯,你也可以做一個構造函數。

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

按照諾曼賓利的建議,你也可以使用數組來保持用戶的互動的軌道與「利」。

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小提琴。

https://jsfiddle.net/3jvbqm9a/

+0

好帖子!如果事件順序無關緊要,則按上述方法使用計數。如果是這樣,你可能需要使用一個數組。 –

+0

@NormanBentley謝謝,對!我將爲此添加一個編輯。 –

+0

非常感謝你@AmreshVenugopal – Chewynugget

0

當然可以。在Javascript中爲dolly創建一個變量/數組。每次您對dolly執行操作時,都將其添加到此數組中。每次讀取數組並確定您的響應應該是什麼。

相關問題