且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript ,事件处理程序总是被调用,即使事件没有被引发

更新时间:2023-11-03 21:15:46

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

The issue here is that when you pass showMessage() as a parameter to focusin, the function showMessage is executed and the return value is passed to focusin.

相反,您需要传递对函数的引用(不带括号).

Instead you need to pass a reference to the function (without the paranthesis).

使用以下代码进行扩展:

Use the following code to extend:

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

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

如果您想将参数传递给 showMessage,请尝试以下操作:

If you want to pass a parameter to showMessage then try this:

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