javascript – 作为JS中另一个函数的参数?

我尝试做这样的事情 Javascript function as a parameter to another function?.但不幸的是我没有成功.我做错了什么,但我不知道是什么.请帮助我!

有一个div元素和一个函数.该函数的作用是:将另一个函数作为参数并在单击div元素时执行它:

UPDATE3:
我已经尝试使用我的原始Web项目获取代码以使用您的示例.但我对一些参数有一些问题.我希望你能像其他人一样快地回答这个问题.

UPDATE4:
谢谢安迪E!和所有其他帮助过我的人!真的很感激!!

!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>

解决方法

将testfunction更改为function并且您将拥有一个作为参数传递的匿名函数.您还需要从exefunction中删除parens(使用它们调用函数而不是赋值):

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

Here is a working example to play around with.

删除你的parens!

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

括号执行函数而不是将其作为参数传递.执行函数时,将传递其返回值.

Second working demo.

对于上次编辑,您需要为代码创建另一个匿名函数:

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

Third (final?) working demo.

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小