2016-08-05 224 views
0

有了這個移除子JS代碼:通過點擊一個按鈕

var prompter = (function(){ 
    var prompt = document.createElement('div'); 
    /* prompt-related stuff */ 

    var closeBtn = document.createElement('button'); 
    /* closeBtn stuff */ 

    prompt.appendChild(closeBtn); 

    this.html = prompt; 

    this.show = (function(){ 
     document.body.appendChild(this.html); 
    }); 

    this.close = (function(){ 
     document.body.removeChild(this.html); 
    }); 
}); 

如果我做

var p = new prompter(); 
    p.show(); 

它確實表明了提詞,如果我做p.close();消失。

但我想要的是,通過點擊closeBtn它確實關閉。我有想到在提示中添加一個id,然後將屬性onclick添加到按鈕,然後通過id執行那些操作,但看起來確實很醜陋...

+3

輝煌的問題標題!我相信很多父母會喜歡這個!大聲笑 – Lee

+0

Caaaaaannnnn呢! –

回答

5

您需要將事件偵聽器添加到您所做的按鈕:

closeBtn.addEventListener("click", this.close.bind(this));