有没有办法将鼠标事件(例如“mouseover”)绑定(bind)到 JavaScript 对象?
function test(x,y,z){
this.x = x;
this.y = y;
this.z = z;
this.add = function(){
$('body').append("<div id='"+this.z+"'>test: x:"+this.x" y:"+this.y"</div>");
}
return this.add();
}
t1 = new test(1,2,3);
t2 = new test(2,3,4);
在我的代码中,我在以下结构中定义了一个类/对象,是否有任何方法可以将事件监听器附加到附加的 div,但能够访问对象属性。
最佳答案
您可以在将其添加到正文后执行此操作,因此在 this.add
函数中您可以绑定(bind)事件:
$("#"+this.z).mouseover(function(){
// Function
});
但是您知道 ID 不能以数字开头吗?
如果您想使用this.z
,请执行此操作。我使用 div[0]
因为所有 jQuery 对象都是数组,所以第 0 个元素是我刚刚创建的元素。
function test(x,y,z){
var div = $("<div id='"+this.z+"'>test: x:"+this.x+" y:"+this.y+"</div>").appendTo("body");
div[0].y = y;
div[0].x = x;
div[0].z = z;
div.mouseover(function(){
alert(this.x);
});
return div;
}
t1 = new test(1,2,3);
t2 = new test(2,3,4);
关于javascript - 将鼠标事件绑定(bind)到 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8247857/