我有一个基于ajax数据绘制html的javascript对象。
然后我尝试使用jquery来处理来自上述对象的实例的html输出上的事件。但是,我想调用一个函数,并从用于绘制html的javascript对象的实例中获取一个属性。
所以我的代码看起来像这样:
function obj1 (){
this.property1 = "propvalue";
this.dosomething = function () {
// does some processing
}
this.drawhtml = function () {
// outputs html
}
}
// jquery to handle events
$(document).ready(function(){
// .edit is a class in the html outputted from the drawhtml
$('body').on('click','.edit',function () {
// call the dosomething from the object
});
});
// create instance of object could be multiple on on page
var instance1 = new obj1;
instance1.drawhtml();
谢谢,
答案 0 :(得分:2)
您可以使用之前创建的实例:
// jquery to handle events
$(document).ready(function(){
// .edit is a class in the html outputted from the drawhtml
$('body').on('click','.edit',function () {
instance1.dosomething();
});
});
// create instance of object could be multiple on on page
var instance1 = new obj1(); // added parentesis so it's valid javascript
instance1.drawhtml();
编辑:从评论开始的其他信息:
处理此问题的最佳方法是将事件处理程序绑定到对象本身。像这样:
function obj1 (){
this.property1 = "propvalue";
this.dosomething = function () {
// does some processing
}
this.drawhtml = function () {
var elem = $("<div>my super dooper HTML</div>");
elem.on('click', this.dosomething);
}
}