JavaScript - onclick事件自动调用 [英] JavaScript - onclick event getting called automatically

查看:132
本文介绍了JavaScript - 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 'm尝试调用如下...

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?

推荐答案

您立即调用该函数。

当你在函数引用上离开括号时,你基本上是说:

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();
    };

这篇关于JavaScript - onclick事件自动调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆