Onclick事件自动被调用 [英] Onclick event getting called automatically
问题描述
我编写了一个名为MyClass
的JavaScript类,在其中定义了方法closeThis
I wrote a JavaScript class called MyClass
in which I've defined a method closeThis
MyClass = function() {
this.closeThis = function() {
document.getElementById("hidePane").style.display = 'none';
}
}
现在,在我的html中,我试图按如下方式调用它...
Now, in my html, i'm trying to call that as follows...
<script type="text/javascript">
function callThis() {
var myclassObj = new MyClass();
document.getElementById("closeButton").onclick = myclassObj.closeThis();
}
</script>
当我单击按钮时,将调用上面的callThis
.这里的问题是,页面加载时会自动调用clsoeButtion
顶部的onclick
事件.这可能是什么问题?
The above callThis
will be called when I clicked on a button. The problem here is, onclick
event on top of clsoeButtion
is getting called automatically when page loads. What could be wrong in this?
推荐答案
您正在立即调用该函数.
You're calling the function right away.
当您在函数引用上保留括号时,您基本上要说的是:
When you leave the parentheses on the function reference, what you're basically saying is:
评估closeThis函数并将结果分配给onclick
Evaluate the closeThis function and assign the result to onclick
当您真正想要做的是将函数引用分配给点击处理程序时:
when what you really want to do is assign the function reference to the click handler:
document.getElementById("closeButton").onclick = myclassObj.closeThis;
改为保留括号,然后将closeThis函数绑定到onclick.相反,这是说:
Leave out the parentheses instead, and you'll bind the closeThis function to the onclick. What this instead says is:
将closeThis函数分配给点击处理程序.
Assign the function closeThis to the click handler.
本质上,您是将函数作为第一类对象或对函数的引用分配给变量.
You are essentially assigning the function to the variable as a first-class object, or a reference to a function.
顺便说一句,我个人的喜好是始终使用匿名函数包装器.有时您需要能够将参数传递到函数中,从而确保可以更轻松地做到这一点:
As an aside, my personal preference is to always use an anonymous function wrapper. Sometimes you need to be able to pass parameters into your function, and this makes sure that you can more easily do so:
document.getElementById("closeButton").onclick =
function() {
myclassObj.closeThis();
};
这篇关于Onclick事件自动被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!