首页 > 解决方案 > 事件声明中是否需要“function()”?

问题描述

我有两个脚本:

<script src="../js/createopp.min.js"></script>
<script src="../js/validation.min.js"></script>

以下行在第一个脚本中,在另一个脚本中调用了一个函数:

$('#places').blur(function(){checkPlacesAvailable()});

如果我将其重写为

$('#places').blur(checkPlacesAvailable());

我在函数上收到“未定义”错误。但是我看到很多使用第二种格式的例子。是否有明显的东西阻止第二个版本在我的情况下工作?

标签: javascriptjquery

解决方案


You should pass function references to event handlers like that.

$('#places').blur(function(){checkPlacesAvailable()});

"is" "equivalent" to this

$('#places').blur(checkPlacesAvailable);

Note that it is not exactly the same because of scopes and all that but most of the times you can pass it in the second manner


推荐阅读