I try to do something like this Javascript function as a parameter to another function?, but unfortunately I haven’t succeeded. I’ve done something wrong, but I don’t know what. Please help me!
There is a div-element and a function. What the function does is: takes an another function as a parameter and execute it on click on the div-element:
UPDATE3:
I’ve tried to get the code to work with your examples beneath, with my original web project. But I’ve got some problem with some parameters. I hope you can answer this question as fast as the others.
UPDATE4:
Thanks Andy E! and all other who have helped me! 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>
change
testfunctiontofunctionand you’ll have an anonymous function that is passed as the argument. You also need to remove the parens fromexefunction(with them the function is called instead of assigned):Here is a working example to play around with.
Remove your parens!
The brackets execute the function instead of passing it as an argument. When you execute a function its return value is passed instead.
Second working demo.
For your last edit, you need to create another anonymous function for the code to work:
Third (final?) working demo.