即使未引发事件,也始终调用Javascript,事件处理程序

我有以下代码扩展了JQuery并为JQuery添加了一个方法:

$.fn.attachWithMessage = function () { $(this).focusin(showMessage()); } function showMessage() { alert('hi'); } 

所以我可以使用以下代码:

  $(document).ready(function () { $("#textbox").attachWithMessage (); }); 

当我第一次加载页面时,会出现一个消息框,显示(’hi’)消息。

即使我没有在文本框中单击。

我也尝试了点击事件,消息仍然自动显示。

有任何想法吗 ??

这里的问题是,当您将showMessage()作为showMessage()的参数focusin ,将执行函数showMessage并将返回值传递给focusin

相反,您需要传递对函数的引用(没有paranthesis)。

使用以下代码进行扩展:

 $.fn.attachWithMessage = function () { $(this).focusin(showMessage); } 

工作示例@ http://jsfiddle.net/eXEP5/

编辑:如果要将参数传递给showMessage,请尝试以下操作:

 $.fn.attachWithMessage = function () { var param1 = "Some Param"; $(this).focusin(function(){ showMessage(param1); //Make sure showMessage is modified accordingly for the parameters. }); } 

只需删除括号

 $(this).focusin(showMessage()); 

应该

 $(this).focusin(showMessage); 

希望这可以帮助