Function as parameter for another function in JS?

Am I trying to make something like a Javascript function as a parameter for another function? . But, unfortunately, I did not succeed. I did something wrong, but I do not know what. Pls help me!

There is a div element and function. What this function does: takes another function as a parameter and executes it when you click on a div element:

Update3: I tried to get the code to work with your examples under my original web project. But I have some problems with some parameters. I hope you can answer this question as quickly as others.

UPDATE4: Thanks Andy E! and to everyone who helped me! I really appreciate it!

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
  <head>


  </head>
  <body>
    <div id='divElement'>Hello World!</div>
    <script type="text/javascript">

        function button(exefunction){
            //Some code that decide which date
            var date = '20101010';
            document.getElementById('divElement').onclick = exefunction(date);
        }
        function testfunction(text){
            document.getElementById('divElement').innerHTML = text;
        }
        button(testfunction);
    </script>
  </body>
</html>
+3
source share
2

testfunction function, , . parens exefunction ( ):

    function button(exefunction){
        document.getElementById('divElement').onclick = exefunction;
    }
    button(function(){
        document.getElementById('divElement').innerHTML = 'Changed';
    });

.


parens!

    button(testfunction);
    // not button(testfunction());

. , .


:

        document.getElementById('divElement').onclick = function () {
            exefunction(date);
        }

(?) .

+5

button(testfunction());

button(testfunction);

, onclick , , -

 function button(exefunction){
        //Some code that decide which date
        var date = '20101010';
        document.getElementById('divElement').onclick = function() {exefunction(date);}
    }
+2

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


All Articles