我有一个名为avatar的JS对象,带有创建函数,该函数在HTML页面上生成一个按钮并设置一些属性。
我想在调用头像对象内的函数的按钮上设置onmouseover,因此我写了:
this.create = function(){
this.button = document.createElement("BUTTON");
this.text = document.createTextNode(this.name);
this.button.appendChild(this.text);
document.body.appendChild(this.button);
this.button.style.background=this.color;
this.button.addEventListener("mouseover", this.randomMove());
}
但是,函数randomMove立即执行,并且不等待按钮被鼠标悬停。随后的鼠标悬停无济于事。
谢谢你的帮助。
事实证明,我真正想要的是绑定。
this.button.addEventListener("mouseover",this.randomMove.bind(this));
这将函数调用绑定到属于该对象的方法。因此,即使生成的HTML不在对象实例的范围内,函数调用仍会记住应对其进行调用的实例。
再次感谢
Ben
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句