Javascript , event handler is always called, even if the event is not raised

白昼怎懂夜的黑 提交于 2019-12-18 09:39:01

问题


i have the following code which extends the JQuery and adds a method to the JQuery:

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

function showMessage() {
    alert('hi');
}

so I can use that code as follows :

<input type="text" name="name" id="textbox" />
$(document).ready(function () {
   $("#textbox").attachWithMessage ();
});

when I load the page for the first time, a message box shows up with ('hi') message.

even if I didn't click in the text box.

I also tried the click event, and the message still shows automatically.

any ideas ??


回答1:


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); 
} 

Working example@ http://jsfiddle.net/eXEP5/

EDIT: 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.
  }); 
} 



回答2:


just remove the parenthesis

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

should be

$(this).focusin(showMessage);

Hope this helps



来源:https://stackoverflow.com/questions/6941622/javascript-event-handler-is-always-called-even-if-the-event-is-not-raised

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!