JS中的OOP方法-将点击动作绑定到Div

JS in OOP approach - binding click action to a Div

本文关键字:绑定 Div OOP 中的 方法 JS      更新时间:2023-09-26

我试图添加一个动作到一个div刚刚创建,但我得到了一些错误,我试图在chrome中使用检查器,看到浏览器正常运行"$(ndiv2).click(function(){ this.dispose() });",错误发生在鼠标单击动作

function gMessageBox(){
this.id=new Date().getTime();
this.boxId="div"+this.id;
this.boxTextId="txt"+this.id;
this.obj=null;
}
gMessageBox.prototype = {
    show: function(message){
        if(document.getElementById("div_messageshow")==null){
        var _body = parent.document.getElementsByTagName('body') [0];
        var ndiv=document.createElement("div");//Container
        var nspan=document.createElement("span")
        nspan.setAttribute("id", this.boxTextId );
        nspan.innerHTML=message;
        ndiv.setAttribute("id", this.boxId );
        var ndiv2=document.createElement("div");//close
        ndiv2.innerHTML="Close";
        ndiv2.setAttribute("style","float: right;cursor:pointer;");
        $(ndiv2).click(function(){ this.dispose() });
        ndiv.appendChild(nspan);
        ndiv.appendChild(ndiv2);
        _body.appendChild(ndiv);
        this.obj=ndiv;
                 }
    },
    dispose: function(){
        alert("dispose");
                    //do sth
    }
};

var mb=new gMessageBox();
mb.show("im message box");

你的问题是,this内的匿名函数你传递作为回调指的是该函数的执行上下文,而不是gMessageBox了。要么做

var that = this;
$(ndiv2).click(function(){ that.dispose(); });

$(ndiv2).click((function(){ this.dispose(); }).bind(this));