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

前端 未结 2 1247
悲哀的现实
悲哀的现实 2020-12-22 10:22

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

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


        
相关标签:
2条回答
  • 2020-12-22 10:29

    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.
      }); 
    } 
    
    0 讨论(0)
  • 2020-12-22 10:43

    just remove the parenthesis

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

    should be

    $(this).focusin(showMessage);
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题