Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 面向对象方法中的JS-将单击操作绑定到Div_Javascript_Oop - Fatal编程技术网

Javascript 面向对象方法中的JS-将单击操作绑定到Div

Javascript 面向对象方法中的JS-将单击操作绑定到Div,javascript,oop,Javascript,Oop,我正在尝试向o刚刚创建的div添加一个操作,但是我在上面遇到了一些错误, 我尝试在chrome中使用inspector,看到浏览器运行“$(ndiv2)。单击(function(){this.dispose()});”正确地说,错误发生在鼠标单击操作中 function gMessageBox(){ this.id=new Date().getTime(); this.boxId="div"+this.id; this.boxTextId="txt"+this.id; this.obj=null

我正在尝试向o刚刚创建的div添加一个操作,但是我在上面遇到了一些错误, 我尝试在chrome中使用inspector,看到浏览器运行
“$(ndiv2)。单击(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(); });


您得到了哪个错误?除了什么错误,您可以使用jsfiddle.net生成重新创建错误的内容吗?未捕获的TypeError:Object#没有方法“dispose”
$(ndiv2).click((function(){ this.dispose(); }).bind(this));