Why does this work:

$("#oneButton").click(function () {
    alert("hello");
}); 

But this doesn't work?

$("#oneButton").click(
    alert("hello");
); 
有帮助吗?

解决方案

The anonymous function route gives a function to be executed later. The second example merely executes code immediately, never waiting for a click event to take place.

The $.fn.click method expects to call a function on your behalf, which will handle the future click event(s). If you give it a number, or a string, or undefined, it will do nothing.

The alert function returns undefined, so your second example is nothing more than:

$("#oneButton").click(undefined);

Note that you don't need to use an anymous function, and in most cases you probably shouldn't. You can use a named function, which helps with debugging down the road:

function handle ( event ) {
    alert( "Clicked" );
}

$("#oneButton").click(handle); // or .click(function handle ( event ) { ... });

In this example, we're passing the function reference to our click event to serve as the handler. Now that jQuery knows of our function, it will execute it when the click event is raised on #oneButton.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top