我有一个名为“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.randomMove()
并将返回的结果分配给 mouseover 事件处理程序。它应该是这样的:
this.button.addEventListener("mouseover", this.randomMove);
请参阅这个简单的示例,轻松了解发生的情况:http://jsfiddle.net/f8tm4jq3/
关于JavaScript 对象。如何创建一个调用同一对象内函数的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408829/