2016-08-05 164 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));