开发者

jQuery event fires on doc ready

I am trying to set the click event of a button on my form and for some reason I am getting weird behavior. When I bind the click event to a function that takes no arguments, things seem to work fine. But when I bind the event with a function that takes an argument, the event fires on document ready and on click. Any ideas?

Example 1:

This causes an alert box to fire on ready and when the button is clicked.

jQuery(document).ready(function(){
   $('myButton').click(alert('foo'));
});

Example 2:

This causes an alert box to fire ONLY when the butt开发者_Go百科on is clicked.

jQuery(document).ready(function(){
   $('myButton').click(wrapper);
});

// External js file
function wrapper(){
   alert('bar');
}


You need an anonymous function (read this for more complete explanation), like this:

jQuery(function() {
  $('myButton').click(function() {
    alert('foo');
  });
});

The click handler takes a function, what happens inside that function is up to you, but it cannot pass events...javascript just doesn't work this way. When you wrap your code in an anonymous function, the whole thing executes, regardless of functions or parameters inside.


$('myButton').click(alert('foo')); calls alert('foo') (popping up a alert), then binds the click event to the return value of alert (which is not the same thing as alert). You'll probably want to use an anonymous function, like Nick suggests.


jQuery(document).ready(function(){
   $('myButton').click(function(){
        wrapper();
    });
});


It's a classical mistake. What you're doing is actually giving the return value in the click event listener, and not the javascript function object.

If you insist on using the upper method, you'll have to use eval (which is best not used)

Your lower method works, and anonymous functions work too.


Wrapper is a Function while Alert is a method of the Window object...

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜