Onclick event getting called automatically(Onclick 事件被自动调用)
问题描述
我编写了一个名为 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 事件被自动调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Onclick 事件被自动调用


- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01