JS中的OOP方法-将点击动作绑定到Div
JS in OOP approach - binding click action to a Div
我试图添加一个动作到一个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));
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- 无法通过数组映射绑定
- 主干-不管怎样,检查事件以前是否绑定过
- 用于搜索的聚合物嵌套绑定
- Angular:更新一次性绑定的数据
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- react.js中的密钥绑定
- 使用regex的jquery keydown绑定不会验证撇号和句点
- 将事件处理程序绑定到任何可能的事件
- AngularJS指令只识别双向绑定类型
- jQuery将更改事件绑定到几个DIV's,但已选定
- 动态插入Div会破坏KnockoutJS数据绑定
- 将DIV元素绑定到溢出滚动条
- 将 jQuery 事件绑定到 DIV 与特定的 HTML 标签,如 TEXTAREA
- 绑定在knockoutjs中拖动DIV元素属性到对象属性
- 在ASP.NET中使用javascript或jquery获取htmleditoreextender内容并绑定到DIV
- JS中的OOP方法-将点击动作绑定到Div
- 绑定了jQuery点击事件的Div在点击时不会触发
- 绑定到Div标签
- 绑定到 DIV 的人道 Js 通知