Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - Onclick event getting called automatically

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...

<script type="text/javascript">
  function callThis() {
    var myclassObj = new MyClass();
    document.getElementById("closeButton").onclick = myclassObj.closeThis();
  }
</script>

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...