Why is function () sometimes required in JavaScript?

HTML

<button id='hello'>Click Me!</button>

JavaScript (wrong)

$('#hello').click(alert('Hello, World!'));

JavaScript (correct)

$('#hello').click(function() {
    alert('Hello, World!');
}

I am wondering why the first JS code starts event loading rather than clicking. Can someone tell me why the function() { [code] }script is necessary for the correct operation?

In this example, I used jQuery events, but this does not apply to it, for example, I also need to use it with setTimeout.

+3
source share
9 answers

The function clickexpects another function as a parameter.

In the first case, you will pass the result of the call alert('hello world');, which is null.

- :

$('#hello').click(callback);

function callback(){
  alert('hello world');
}
+12

.click() . - . , ( alert), .

$('#hello). click (function() {}) ` :

var myfunction = function() { 
  // code
};

$('#hello').click( myfunction );

, .

+2

: "

alert ('Hello, World!')

, . "

: " , , , .

+2

function() { ... } , Javascript. jQuery , , - , , . , . , , , , .

: " JavaScript , ?" :

function returnCallback(linkId, data) {
    return function(e) {
        alert('Clicked on ' + linkId + '.  Here is some data: ' + data);
        // Maybe do some stuff with e, the event parameter
    }
}

$('#some-link').click(returnCallback('some-link', 'some-data'));

$('#other-link').click(returnCallback('other-link', 'different-data'));

, . , returnCallback .

+2

, "JavaScript ", alert('Hello, World!') , script. , .click, - , . , ( ) , .

$('#hello').click(alert('Hello, World!')); alert('...') .click(), .

+1

, JavaScript , . , , :

<script language="javascript" type="text/javascript">

    $("#mybutton").click(clickFired);


    function clickFired() {

        alert('click fired');
    }

</script>
+1

, .click(), . $( "# hello" ). Click (function {[code]}); . alert().

0

click .

( "" ) alert('Hello, World!'), , , , .

( "" ) , , . , , .

0

somefunction (alert ('hello! world'));

, - ( "! " ).

jquery click , . , , - ( jquery) .

0

Source: https://habr.com/ru/post/1774118/


All Articles