JavaScript - onclick event getting called automatically

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

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';  }  }

Now, in my html, i'm trying to call that as follows...

 

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?

回答1:

You're calling the function right away.

When you leave the parentheses on the function reference, what you're basically saying is:

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;

Leave out the parentheses instead, and you'll bind the closeThis function to the onclick. What this instead says is:

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


回答2:

it should be document.getElementById("closeButton").onclick = myclassObj.closeThis; not myclassObj.closeThis();

myclassObj.closeThis() will call the function then assign value to onclick



回答3:

You need to remove () from it otherwise it gets called immediately because that's how you call a function by suffixing (), so simply remove these braces:

document.getElementById("closeButton").onclick = myclassObj.closeThis;


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!